-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWithoutRecursion.java
More file actions
104 lines (73 loc) · 2.22 KB
/
ReverseWithoutRecursion.java
File metadata and controls
104 lines (73 loc) · 2.22 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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Dell
*/
class Reverse{
int data;
Reverse next;
}
public class ReverseWithoutRecursion {
Reverse tail;
Reverse head;
public void insert(int data){
if(head == null){
Reverse first = new Reverse();
first.data = data;
first.next = head;
head = first;
tail = first;
}
else{
Reverse temp = head;
Reverse temp2 = new Reverse();
while(temp.next != null){
temp = temp.next;
}
temp2.data = data;
temp2.next = null;
temp.next = temp2;
tail = temp2;
}
}
public void print(){
Reverse temp = head;
while(temp != null){
System.out.print(temp.data + "->");
temp = temp.next;
}
}
public void reverse(){
while(head.next != null){
Reverse temp = head;
Reverse temp2 = head;
while(temp2.next != null){
temp = temp2;
temp2 = temp2.next;
}
temp2.next = temp;
temp.next = null;
}
}
public void printReverse(){
while(tail != null){
System.out.print(tail.data + "->");
tail = tail.next;
}
}
public static void main(String[] args){
ReverseWithoutRecursion rwr = new ReverseWithoutRecursion();
rwr.insert(5);
rwr.insert(10);
rwr.insert(15);
rwr.insert(25);
rwr.print();
System.out.println("\nNow printing the list in reverse manner :: ");
rwr.reverse();
rwr.printReverse();
}
}