链表的反转

引言

  • 本文展示了链表的反转的代码,用递归和非递归的方式实现。
  • 详细的链表反转见leetcode 206的解法。

递归的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null) return null;
if(head.next==null) return head;

ListNode p = head.next;
ListNode n = reverseList(p);

head.next = null;
p.next = head;
return n;
}
}

非递归的实现

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}

ListNode point1 = head;
ListNode point2 = head.next;
ListNode point3 = (point2==null)?null:point2.next;

while(point2!=null){
//System.out.println("----");
point3 = point2.next;
point2.next = point1;
point1 = point2;
point2 = point3;
}
head.next=null;

return point1;
}
}
您的支持是对我最大的鼓励!