206. Reverse Linked List
Reverse a singly linked list.
/**
* 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 *dummy = new ListNode(-1);
dummy->next = head;
ListNode *cur = head;
ListNode *after = cur->next;
while(after){
//将after插入到dummy后面
cur->next = after->next;
after->next = dummy->next;
dummy->next = after;
//
after = cur->next;
}
return dummy->next;
}
};
遍历,头插
/**
* 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) {
ListNode* newHead = NULL;
ListNode* temp =NULL;
while(head != NULL){
temp = head;
head = head->next;
//将节点插入到新链表的头部
temp->next = newHead;
newHead = temp;
}
return newHead;
}
};
递归的方法
/**
* 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 *newHead = reverseList(head->next);
//此时head->next已经成为上述链表的尾节点
head->next->next = head;
//这句也很重要啊
head->next = NULL;
return newHead;
}
};