-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathAdded Reverse Linked List in java
54 lines (43 loc) · 1.3 KB
/
Added Reverse Linked List in 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
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public Node reverseLinkedList(Node head) {
Node prev = null;
Node current = head;
while (current != null) {
Node nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
return prev; // New head of the reversed list
}
public void printLinkedList(Node head) {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.print("null\n");
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
System.out.println("Original linked list:");
list.printLinkedList(list.head);
Node reversedHead = list.reverseLinkedList(list.head);
System.out.println("Reversed linked list:");
list.printLinkedList(reversedHead);
}
}