forked from ossamamehmood/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseLL.java
67 lines (57 loc) · 1.42 KB
/
reverseLL.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
55
56
57
58
59
60
61
62
63
64
65
66
67
//Reverse a Linked list
public class LinkedList {
// To create a Linked List
static Node head;
static class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}
// Reverse Method
Node reverseList(Node node) {
Node curr = node, next = null, prev = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
node = prev;
return prev;
}
// To display the Linked List
void display(Node data) {
while (data != null) {
System.out.print(data.val + " ");
data = data.next;
}
}
// Main Method
public static void main(String argvs[]) {
LinkedList list = new LinkedList();
list.head = new Node(4);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(5);
list.head.next.next.next.next = new Node(7);
System.out.println("Original Linked list : ");
list.display(head);
head = list.reverseList(head);
System.out.println("\n");
System.out.println("Reversed Linked list : ");
list.display(head);
}
}
/*
* Output:
*
* Original Linked list :
* 4 2 3 5 7
*
* Reversed Linked list :
* 7 5 3 2 4
*
*/