剑指24:反转链表

传送门

nowcoder
leetcode

题目描述

输入一个链表,反转链表后,输出新链表的表头。

C++ 代码 - nowcoder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
头插法,新建一个虚拟头节点
*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == nullptr || pHead->next == nullptr) return pHead;

ListNode *dummy = new ListNode(-1), *p = pHead;
dummy->next = nullptr;
while (p != nullptr) {
ListNode* q = p;
p = p->next;
q->next = dummy->next;
dummy->next = q;
}
return dummy->next;
}
};

/*
三个指针
*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == nullptr || pHead->next == nullptr) return pHead;

ListNode *prev = nullptr, *cur = head, *next = nullptr;
while (cur != nullptr) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};

C++ 代码 - leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
三个指针
*/
class Solution {
public:
ListNode* trainningPlan(ListNode* head) {
if (!head || !head->next) return head;

ListNode *prev = nullptr, *cur = head, *next = nullptr;
while (cur != nullptr) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};

/*
递归实现
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;

ListNode* last = reverseList(head->next);
head->next->next= head;
head->next = nullptr;
return last;
}
};

剑指24:反转链表
https://lcf163.github.io/2021/01/30/剑指24:反转链表/
作者
乘风的小站
发布于
2021年1月30日
许可协议