206. Reverse Linked List

问题
Given the head of a singly linked list, reverse the list, and return the reversed list.

翻转列表,当链表长度不足时,直接返回原链表。
将头元素设置到preNode,同时将其next设置为null,作为新链表的尾。
将其余的元素设置到curNode。

当当前节点不为null时
遍历:

  1. 将curNode的next保存在temp。
  2. 将curNode的next指向preNode,作为preNode的上一个节点。
  3. 将preNode指向curNode,完成交换。
  4. 将curNode指向temp,curNode变为原来的curNode的next。
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
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {

if( head == null ){ //if not enough, return head
return head;
}
if ( head.next == null ){
return head;
}

ListNode preNode = head; //set head to preNode, it will be the last node in the end
ListNode curNode = head.next; //curNode move to next
preNode.next = null; //only preserve one head node
ListNode temp;

while( curNode != null ){
temp = curNode.next; //preserve nodes after curNode
curNode.next = preNode; //cur -> pre
preNode = curNode; //set back reversed list to preNode
curNode = temp; //put back preserved nodes, curNode move to the next
}
return preNode;
}

}
Author

Xander

Posted on

2022-04-10

Updated on

2022-04-09

Licensed under

Comments