forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseList.java
More file actions
55 lines (50 loc) · 1.49 KB
/
ReverseList.java
File metadata and controls
55 lines (50 loc) · 1.49 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package normal;
/**
* @program JavaBooks
* @description: 206.反转链表
* @author: mf
* @create: 2019/11/05 19:36
*/
/*
题目:https://leetcode-cn.com/problems/reverse-linked-list/comments/
类型:链表
难度:easy
*/
public class ReverseList {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
ListNode head = ListNode.setListNode(arr);
ListNode l = reverseList2(head);
ListNode.printNode(l);
}
/**
* 递归优点绕,还是用循环好理解一些
* @param head
* @return
*/
private static ListNode reverseList(ListNode head) {
ListNode pre = null; // 当前节点的前一个节点
ListNode cur = head; // 当前节点
while (cur != null) {
ListNode nextTemp = cur.next; // 先保存当前节点的下一个节点
cur.next = pre; // 将当前节点的下个节点指向前一个节点pre
pre = cur; // 将pre往后移动指向当前节点
cur = nextTemp; // 将当前指点指针往后移动next
}
return pre;
}
/**
* 尾递归
* @param head
* @return
*/
private static ListNode reverseList2(ListNode head) {
return reverse(null, head);
}
private static ListNode reverse(ListNode pre, ListNode cur) {
if (cur == null) return pre;
ListNode next = cur.next; // 保存当前节点的下个节点的指针
cur.next = pre;
return reverse(cur, next);
}
}