迭代
每次修改两个结点之间的指向关系。
/**
* 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 || !head->next){
return head;
}
ListNode* a = head, *b = head->next;
while(b)
{
ListNode* p = b->next;
b->next = a;
a = b;
b = p;
}
head->next = NULL;
return a;
}
};
递归
当‘递’到尾结点之后开始‘归’,每次归的时候都head->next->next=head;
并且head->next=NULL;
。最后将头节点的next改为NULL,返回结尾。
/**
* 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 || !head->next){
return head;
}
ListNode* tail = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return tail;
}
};
反转链表II
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if (!head || !head->next) return head;
ListNode* p = new ListNode;
p->next = head;
head = p;
for (int i = 0; i < left - 1; ++i){
p = p->next;
}
ListNode* a = p, *b = a->next, *c = b->next;
for (int i = 0; i < right - left; ++i){
ListNode* d = c->next;
c->next = b;
b = c, c = d;
}
a->next->next = c;
a->next = b;
return head->next;
}
};