LinkReverse

题目描述[原题链接][https://www.acwing.com/problem/content/description/33/]

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

样例

1
2
3
输入:1->2->3->4->5->NULL

输出:5->4->3->2->1->NULL

算法描述

分析题意可知,本题的难点在于当你将节点的指针反向后,后面的节点可能会找不到了,所以再反转的过程中需要将后面的节点先保存起来,每次操作涉及到的节点有三个,所以需要维护一个三个节点的窗口,直到遍历到链表尾部,如果第三个节点的值为空,将第二个节点的next指向第一个节点

C++代码

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
/**
* 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;
auto dummy = new ListNode(-1);
dummy->next = head;
auto pre = dummy,curr = dummy->next;
while(curr->next){
auto temp = curr->next;
curr->next = pre;
pre = curr;
curr = temp;
}
curr->next = pre;
head->next = NULL;
return curr;
}
};

Java代码

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null)return head;
ListNode dummy = new ListNode(-1);
dummy.next=head;
ListNode p = dummy;
ListNode q = dummy.next;
while(q.next!=null){
ListNode t = q.next;
q.next=p;
p=q;
q=t;
}
q.next=p;
head.next=null;
return q;
}
}