-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseALinkedList.java
69 lines (63 loc) · 1.58 KB
/
ReverseALinkedList.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
68
69
import java.util.Scanner;
class Node{
int data;
Node next;
}
class ReverseALinkedList{
static Node head = null;
static Scanner scan = new Scanner(System.in);
static void push(){
Node newNode = new Node(),temp = head;
newNode.data = scan.nextInt();
newNode.next = null;
if(temp==null){
head = newNode;
}else{
while(temp.next!=null) {
temp = temp.next;
}
temp.next = newNode;
}
System.out.println("Data added to Linked List");
}
static void print(){
Node temp = head;
if(temp==null)
System.out.println("Linked list is empty");
else{
while(temp!=null){
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
}
static void reverse(){
Node temp = head, t1 = null, t2 = null;
while(temp!=null){
t2 = temp.next;
temp.next = t1;
t1 = temp;
temp = t2;
}
head = t1;
}
public static void main(String args[]){
while(true){
int x = scan.nextInt();
switch(x){
case 1:
push();
break;
case 2:
print();
break;
case 3:
reverse();
break;
default:
System.out.println("Invalid Command");
}
}
}
}