1,题目要求
输入一个链表,反转链表后,输出新链表的表头。
2,题目思路
对于这道题,是单链表问题的一个非常经典的问题。一般来说,这个问题有两种解决办法:迭代与递归。
迭代:
迭代的方法相对来说比较简单。
我们首先定义一个节点,作为开始节点(NULL),然后在循环的过程中:
- 记录当前节点的下一个节点。
- 让当前节点指向上一个节点。
- 让当前节点变为下一个节点。
这样,在对该单链表遍历一遍之后,就可以将这个链表翻转了。
递归:
递归的方法稍微比较难理解一些。
这里利用LeetCode上一位国人的讲解:
- Step 1:Base Case
if(!head || !head->next)
return head;
可以看到,Base Case的返回条件是当head或者head->next为空,则开始返回。
- Step 2:Recurse到底
ListNode *newHead = reverseList(head->next);
在做任何处理之前,我们需要不断的进行递归,知道触及到Base Case。当我们移动到最后一个Node时,就将这个Node定义为newHead,并从newHead开始,重复性的往前更改指针的方向。
- Step 3:返回并更改指针的方向
head->next->next = head;
#2 head->next = NULL;
#3 return newHead;
经过这样的递归后,就可以成功的将该单链表逆置了。
3,代码实现
1,非递归
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr)
return nullptr;
ListNode* curr = nullptr;
while(pHead){
ListNode* next = pHead->next;
pHead->next = curr;
curr = pHead;
pHead = next;
}
return curr;
}
};
2,递归
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead || !pHead->next)
return pHead;
ListNode* newHead = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = nullptr;
return newHead;
}
};