-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListans6.java
More file actions
72 lines (65 loc) · 1.49 KB
/
Copy pathListans6.java
File metadata and controls
72 lines (65 loc) · 1.49 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
public class Listans6 {
class Node{
String data;
Node next;
Node(String data){
this.data = data;
this.next = null;
}
}
// Add Node
Node head;
public void addfirst(String data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
// print Node
public void printList(){
if(head == null){System.out.print("List is Empty");}
Node currNode = head;
while(currNode != null){
System.out.print(currNode.data + " -> ");
currNode = currNode.next;
}
System.out.println(" null");
}
// Reverse List Iterative Method
public void reverselist(){
Node prevNode = head;
Node currNode = head.next;
while(currNode != null){
Node nextNode = currNode.next;
currNode.next = prevNode;
// Update
prevNode = currNode;
currNode = nextNode;
}
head.next = null;
head = prevNode;
}
public Node recursiveLL(Node head){
if(head == null || head.next == null){
return head;
}
Node newHead = recursiveLL(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public static void main(String[] args){
Listans6 list = new Listans6();
list.addfirst("Song A");
list.addfirst("Song B");
list.addfirst("Song C");
list.addfirst("Song D");
list.printList();
// list.reverselist();
list.head = list.recursiveLL(list.head);
list.printList();
}
}