当前位置: 代码迷 >> 综合 >> C++ 单向链表倒置 reverse
  详细解决方案

C++ 单向链表倒置 reverse

热度:46   发布时间:2023-11-18 01:13:45.0
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};

现在才知道大学学的基础知识这两年都没怎么用,都快忘完了,今天刷leetcode发现单向链表reverse都快写不出来了hhhh。

1) 递归方法:

class Solution {
public:ListNode* reverseList(ListNode* head) {if (!head || !head->next)return head;ListNode *p = head;head = reverseList(p->next);p->next->next = p;p->next = NULL;return head;}
};

2)三指针操作

ListNode* reverseBetween(ListNode* head, int m, int n) {if (!head) {return head;}ListNode* pre, *cur, *next;pre = head;cur = head->next;while (cur) {next = cur->next;cur->next = pre;pre = cur;cur = next;}pre->next = NULL;head = pre;return head;}

3) 

class Solution {
public:ListNode* reverseList(ListNode* head) {if (!head) return head;ListNode *dummy = new ListNode(-1);dummy->next = head;ListNode *cur = head;while (cur->next){ListNode *tmp = cur->next;cur->next = tmp->next;tmp->next = dummy->next;dummy->next = tmp;}return dummy->next;}
};