-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-linked-list.java
47 lines (39 loc) · 1.04 KB
/
reverse-linked-list.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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
/* O(n) space complexity - Stack Solution
Stack<Integer> stack = new Stack<Integer>();
ListNode cur = head;
while(cur!=null ){
stack.push(cur.val);
cur = cur.next;
}
cur = head;
while(!stack.isEmpty()){
cur.val = stack.pop();
cur = cur.next;
}
return head;
*/
if(head == null || head.next == null)
return head;
ListNode prev = null;
ListNode cur = head;
ListNode cur_next = cur.next;
while(cur.next!=null){
cur.next = prev;
prev = cur;
cur = cur_next;
cur_next = cur_next.next;
}
cur.next = prev;
return cur;
}
}