leetcode206_翻转列表
一、题目

二、想法分析
我的直接的一个想法是,可以设置一个vector,然后把数据读取出来,然后重新赋值就好了。
另外需要注意一下,如果是存在头节点,那么判断链表是否为空的时候,可以如下判断:
if(head->next == NULL)
如果链表不存在头节点,那么可以直接判断:
if(head == NULL)
三、代码
/** * 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* reverseList(ListNode* head) { //如果为空,则返回 if(head == nullptr) //这个程序是不带头节点的,不带的话就直接判断head是否为空 return head; ListNode* pre = head; vector<int> num; int count = 0; while(pre->next != nullptr) { num.push_back(pre->val); pre = pre->next; count++; } num.push_back(pre->val); pre = head; while(pre->next != nullptr){ pre->val = num[count--]; pre = pre->next; } pre->val = num[count]; return head; } };
四、参考思路与代码
参考思路为使用双节点方法,调整链表的方向;
或者是使用递归,也是直接调整方向。
双节点
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* temp; // 保存cur的下一个节点 ListNode* cur = head; ListNode* pre = NULL; while(cur) { temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next cur->next = pre; // 翻转操作 // 更新pre 和 cur指针 pre = cur; cur = temp; } return pre; } };
递归
class Solution { public: ListNode* reverse(ListNode* pre,ListNode* cur){ if(cur == NULL) return pre; ListNode* temp = cur->next; cur->next = pre; // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步 // pre = cur; // cur = temp; return reverse(cur,temp); } ListNode* reverseList(ListNode* head) { // 和双指针法初始化是一样的逻辑 // ListNode* cur = head; // ListNode* pre = NULL; return reverse(NULL, head); } };
纵一苇之所如,临万顷之茫然。

浙公网安备 33010602011771号