-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathReverse.java
65 lines (57 loc) · 1.29 KB
/
Reverse.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
import java.util.*;
class Reverse{
Node head;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public void add_ele(int data){
Node newnode = new Node(data);
if(head==null){
head=newnode;
return;
}
Node temp=head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=newnode;
}
public void reverse_list(){
Node prev=null;
Node curr= head;
Node next=null;
while(curr!=null){
next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
head=prev;
}
public void print(){
Node temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
public static void main(String [] args){
Reverse list = new Reverse();
Scanner sc = new Scanner(System.in);
int size=sc.nextInt();
for(int i=0;i<size;i++){
int a=sc.nextInt();
list.add_ele(a);
}
System.out.println("Linked list before reversing");
list.print();
list.reverse_list();
System.out.println("Linked list after reversing");
list.print();
}
}