-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[206]反转链表.java
More file actions
59 lines (50 loc) · 1.2 KB
/
Copy path[206]反转链表.java
File metadata and controls
59 lines (50 loc) · 1.2 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
56
57
58
59
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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) {
// // base case
// if (head == null || head.next == null) {
// return head;
// }
//
//
// //先定义一个反转链表的函数,其意义是给一个头指针,然后返回一个反转链表的尾指针
// ListNode last = reverseList(head.next);
//
// //指针反向指向
// head.next.next = head;
//
// //head指向NULL
// head.next = null;
// return last;
//
//}
//解法二:
public ListNode reverseList(ListNode head) {
//三个指针
ListNode pre = null;
ListNode nxt = head;
ListNode cur = head;
while (cur != null) {
//nxt指针移动到下一位
nxt = cur.next;
//pre指向到nxt指针
cur.next = pre;
pre = cur;
//nxt就是当前的指针
cur = nxt;
}
return pre;
}
}
//leetcode submit region end(Prohibit modification and deletion)