forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedListReverse.java
87 lines (70 loc) · 1.37 KB
/
linkedListReverse.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.util.Scanner;
public class linkedListReverse {
static Node head;
class Node{
public int data;
public Node next;
Node(int data){
this.data=data;
}
}
void add(int data)
{ Node ctr=head;
Node ptr = new Node(data);
if(ctr==null)
{
head=ptr;
ptr.next=null;
}
else
{
while(ctr.next!=null)
ctr=ctr.next;
ctr.next=ptr;
ptr.next=null;
}
}
public void print() {
Node ctr=head;
while(ctr!=null)
{
System.out.print(ctr.data+" ");
ctr=ctr.next;
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
linkedListReverse ll = new linkedListReverse();
String choice;int data;
System.out.println("Enter y to add a data to Linked List");
choice = sc.nextLine();
while(!choice.isEmpty() && choice.charAt(0)=='y') {
System.out.println("Enter data to enter into the linked list");
data=sc.nextInt();
ll.add(data);
ll.print();
System.out.println();
System.out.println("Enter y to add a data to Linked List");
sc.nextLine();
choice = sc.nextLine();
}
Node ctr=head;Node ptr,temp;
if(ctr==null)
System.out.println("Linked List is empty");
else {
ptr=null;
temp=ctr.next;
while(ctr.next!=null)
{
ctr.next=ptr;
ptr=ctr;
ctr=temp;
temp=temp.next;
}
ctr.next=ptr;
head=ctr;
ll.print();
}
}
}