反转链表
迭代
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* p = head;
ListNode* q = p->next;
ListNode* o = q->next;
p->next = NULL;
while(o != NULL)
{
q->next = p;
p = q;
q = o;
o = o->next;
}
q->next = p;
return q;
}
};
递归
画图方便理解
不断返回原链表的尾节点
每次返回的过程中顺便更改节点间连接关系
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};