-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
107 lines (94 loc) · 2.87 KB
/
Copy pathReverseLinkedList.java
File metadata and controls
107 lines (94 loc) · 2.87 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.*;
class LinkLi {
class Node {
int info;
Node link;
Node(int data) {
this.info = data;
this.link = null;
}
}
Node first;
void insertAtFirst(int data) {
Node newNode = new Node(data);
if (first == null) {
first = newNode;
return;
}
// newNode.info = data;
newNode.link = first;
first = newNode;
}
void insertAtLast(int data) {
Node newNode = new Node(data);
if (first == null) {
first = newNode;
return;
}
Node currentNode = first;
while (currentNode.link != null) {
currentNode = currentNode.link;
}
currentNode.link = newNode;
}
void revLink() {
if (first == null || first.link == null) {
System.out.println("Empty");
return;
} else {
Node prevNode = first;
Node currNode = first.link;
while (currNode != null) {
Node nextNode = currNode.link;
currNode.link = prevNode;
prevNode = currNode;
currNode = nextNode;
}
first.link = null;
first = prevNode;
}
}
void printList() {
if (first == null) {
System.out.println("List Is Empty");
}
Node currentNode = first;
while (currentNode != null) {
System.out.print(currentNode.info + " -> ");
currentNode = currentNode.link;
}
System.out.println("NULL");
}
public class ReverseLinkedList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkLi lists = new LinkLi();
System.out.println("LinkedList Operation :");
while (true) {
System.out.println("\n1. Insert at First");
System.out.println("2. Insert at Last");
System.out.println("2. Reverse List");
System.out.println("2. Print List");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter data to insert at first: ");
int data = sc.nextInt();
lists.insertAtFirst(data);
break;
case 2:
System.out.print("Enter data to insert at last: ");
data = sc.nextInt();
lists.insertAtLast(data);
break;
case 3:
lists.revLink();
break;
case 4:
lists.printList();
break;
}
}
}
}
}