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 *new_prev = head->next; //存储新构成的链表的最后一个节点
ListNode *new_head = reverseList(head->next); //反转从下一个节点开始的链表
new_prev->next = head;
head->next = NULL;
return new_head;
}
};
迭代算法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL) return head;
ListNode dummy(-1);
dummy.next = head;
ListNode *head2 = &dummy;
ListNode *prev = head2->next;
ListNode *cur = prev->next;
while(cur != NULL){
prev->next = cur->next;
cur->next = head2->next;
head2->next = cur; //头插法
cur = prev->next;
}
return dummy.next;
}
};
[LeetCode] 206. Reverse Linked List
原文:https://www.cnblogs.com/wengle520/p/12309395.html