AcWing 35. 反转链表
原题链接
简单
作者:
SayYong
,
2024-10-18 09:33:17
,
所有人可见
,
阅读 2
反转链表
头插法
/**
* 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* dummy = new ListNode(-1);
dummy->next = NULL;
ListNode* cur = dummy;
while (head) {
ListNode* node = new ListNode(head->val);
node->next = cur->next;
cur->next = node;
head = head->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* prev = nullptr;
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next;
cur->next = prev;
prev = cur, cur = next;
}
return prev;
}
};
递归法
/**
* 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;
}
};