-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse Linked List.java
More file actions
46 lines (37 loc) · 1.08 KB
/
Reverse Linked List.java
File metadata and controls
46 lines (37 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
// 206. Reverse Linked List (https://leetcode.com/problems/reverse-linked-list)
// 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) {
int[] nodeVal = new int[5000];
int size = 0;
for (ListNode node = head; node != null; node = node.next) {
nodeVal[size++] = node.val;
}
ListNode res = new ListNode(nodeVal[size-1]);
ListNode pos = res;
for (int i = size-2; i >= 0; i--, pos = pos.next) {
pos.next = new ListNode(nodeVal[i]);
}
return res;
}
}
class Solution2 {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}