剑指 Offer 24. 反转链表
题目链接
方法一:翻转当前节点的后一个节点指向,让其指向头部。
/**
* 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* pre = new ListNode();
pre->next = head;
ListNode* cur = head;
while(cur != nullptr && cur->next != nullptr)
{
ListNode* p = cur->next;
cur->next = cur->next->next;
p->next = pre->next;
pre->next = p;
}
return pre->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* pre = nullptr;
ListNode* cur = head;
ListNode* ans = nullptr;
while(cur != nullptr)
{
ListNode* p = cur->next;
cur->next = pre;
ans = cur; // 保存最后一个值,便于返回答案
pre = cur;
cur = p;
}
return ans;
}
};
两种方法类似,如果有其他更好的方法,欢迎评论!