-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT206.java
More file actions
57 lines (47 loc) · 1.08 KB
/
T206.java
File metadata and controls
57 lines (47 loc) · 1.08 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
/*
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
*/
// Definition for singly-linked list.
class Solution {
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;
}
}
public ListNode reverseList(ListNode head) {
//保证有两个及以上的节点
if(head == null || head.next == null){
return head;
}
//双指针法
ListNode pre = null,cur = head;
while (cur != null) {
//在纸上写一下伪代码梳理一下思路就很快
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
//返回pre就行
// if(temp == null){
// return cur;
// }
cur = temp;
}
return pre;
}
}