-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0206.java
43 lines (40 loc) · 944 Bytes
/
0206.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
/**
* 非递归方法
*/
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode p = head;
ListNode nHead = null;
ListNode pTmp = null;
while(p != null){
pTmp = p.next;
p.next = nHead;
nHead = p;
p = pTmp;
}
return nHead;
}
/**
* 递归方法
*/
public ListNode reverseList2(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode ln = reverseList2(head.next);
head.next.next = head;
head.next = null;
return ln;
}
}