问题描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解法一:
扫描一遍,每扫描到一个节点,就将这个节点与下个节点的方向颠倒一下,扫描一遍之后就实现了反转。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *current = head;//当前的节点
ListNode *temp_next;
ListNode *preview = NULL;//前边的节点
while(current != NULL){
temp_next = current->next;
current->next=preview;
preview=current;
current=temp_next;
}
return preview;
}
};
自己画的原理图如下(太难看了,自己都看不下去了):
解法二:
把上面的代码修改成使用递归的方法。
可以加一个“哑结点”指向头结点。
代码如下:
ListNode* reverseList(ListNode* head) {
if(!head){
return nullptr;
}
return reverse(head, head, head->next);
}
ListNode* reverse(ListNode* head, ListNode* first, ListNode* target){
if(!target){
return head;
}
first->next = target->next;
ListNode* temp = target->next;
target->next = head;
return reverse(target, first, temp);
}
这个递归代码参考大佬的:
作者:sunshy
链接:https://leetcode-cn.com/problems/two-sum/solution/die-dai-di-gui-jie-fa-by-sunshy/
解法三:
力扣官方的递归方法:
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode *p = reverseList(head->next);
head->next ->next = head;
head->next = NULL;
return p;
}
};