-
Notifications
You must be signed in to change notification settings - Fork 21
/
_0206_ReverseLinkedList.java
77 lines (68 loc) · 1.6 KB
/
_0206_ReverseLinkedList.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package leetcode;
/**
* @No 206
* @problem Reverse Linked List
* @level Easy
* @desc 反转链表
* @author liyazhou1
* @date 2017/08
*
* <pre>
* Reverse a singly linked list.
*
* Example:
* Input: 1->2->3->4->5->NULL
* Output: 5->4->3->2->1->NULL
*
* Follow up:
* A linked list can be reversed either iteratively or recursively. Could you implement both?
* </pre>
*/
public class _0206_ReverseLinkedList {
/**
* Note
*
* Thought
*
* Challenge
*
* Algorithm
* 1.
* 2.
*
* Complexity
* Time,
* Space,
*/
private static class Solution {
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode tmpNode = curr.next;
curr.next = prev;
prev = curr;
curr = tmpNode;
}
return prev;
}
public ListNode reverseList1(ListNode head) {
if (head == null || head.next == null) return head;
ListNode first = head;
first.next = null;
ListNode second = head.next;
while (second != null){
ListNode tempNode = second.next;
second.next = first;
first = second;
second = tempNode;
}
return first;
}
}
}