-
Notifications
You must be signed in to change notification settings - Fork 87
/
LinkedListReversal.java
51 lines (41 loc) · 1.24 KB
/
LinkedListReversal.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
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class LinkedListReversal {
public ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
public void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
LinkedListReversal reversal = new LinkedListReversal();
System.out.println("Original List:");
reversal.printList(head);
System.out.println();
ListNode reversedHead = reversal.reverse(head);
System.out.println("Reversed List:");
reversal.printList(reversedHead);
}
}