-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinked.java
More file actions
55 lines (45 loc) · 1.43 KB
/
Copy pathReverseLinked.java
File metadata and controls
55 lines (45 loc) · 1.43 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
package LeetcodePractice;
public class ReverseLinked {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // Save next
curr.next = prev; // Reverse link
prev = curr; // Move prev forward
curr = next; // Move curr forward
}
return prev; // New head
}
public static ListNode createList(int[] values) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int val : values) {
current.next = new ListNode(val);
current = current.next;
}
return dummy.next;
}
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val);
if (head.next != null) System.out.print(" -> ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
int[] input = {1, 2, 3, 4, 5};
ListNode head = createList(input);
System.out.print("Original List: ");
printList(head);
head = reverseList(head);
System.out.print("Reversed List: ");
printList(head);
}
}