题目描述
示例:
代码:
方法一:
- 定义三个指针,整体右移,边移动,边翻转,保证不会断链
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == nullptr || pHead->next == nullptr) {
return pHead;
}
ListNode * first = pHead;
ListNode* second = first->next;
ListNode* third = second->next;
while (third) {
second->next = first;
first = second;
second = third;
third = third->next;
}
second->next = first;
pHead->next = nullptr;
pHead = second;
return pHead;
}
};
- 可以采用头插思想进行翻转
class Solution {
public:
ListNode* ReverseList(ListNode* pHead)
{
if (pHead == nullptr || pHead->next == nullptr)
return pHead;
ListNode* new_head = nullptr;
while (pHead != nullptr) {
ListNode* p = pHead;
pHead = pHead->next;
p->next = new_head;
new_head = p;
}
pHead = new_head;
return pHead;
}
};