1. 输入一个链表,反转链表后,输出新链表的表头
2. Code
注意保存需要用到的节点后再断开,否则后续无法连接
(1)非递归
```
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* new_head = NULL;
ListNode* tmp = NULL;
while(pHead){
tmp = pHead->next;
pHead->next = new_head;
new_head = pHead;
pHead = tmp;
}
return new_head;
}
};
```
(2)递归
递归可能不是很好理解,就是一直处理到边界条件找到出口,再一层一层的向上返回~暂且画个图来解释
如图所示,当phead
递归到节点3的时候,res
返回的结果是节点4,此时pHead->next->next = pHead
这行代码就是将4的next
指针指向phead节点,同时不要忘记将phead
的next指针指向NULL
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL) return pHead;
ListNode* res = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return res;
}
};