-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverselist.java
More file actions
69 lines (64 loc) · 1.47 KB
/
Copy pathreverselist.java
File metadata and controls
69 lines (64 loc) · 1.47 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
public class reverselist {
private int size;
reverselist(){
this.size = 0;
}
class Node{
String data;
Node next;
Node(String data){
this.data = data;
this.next = null;
size++;
}}
// Add Node
public int getSize(){
return size;
}
Node head;
public void addFirst(String data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
// Print List Of Node
public void printList(){
Node currNode = head;
while(currNode != null){
System.out.print(currNode.data + " ->");
currNode = currNode.next;
}
System.out.println("null");
}
// ReverseList
public void reverseListIterative(){
Node prevNode = head;
Node currNode = head.next;
while(currNode != null){
Node nextNode = currNode.next;
currNode.next = prevNode;
// Updating
prevNode = currNode;
currNode = nextNode;
}
head.next = null;
head = prevNode;
}
public static void main(String[] args){
reverselist list = new reverselist();
list.addFirst("Song A");
list.addFirst("Song B");
list.addFirst("Song C");
list.addFirst("Song D");
list.addFirst("Song E");
list.addFirst("Song F");
list.printList();
list.reverseListIterative();
list.printList();
System.out.println("Size Of Node " + list.getSize());
}
}