-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedList.java
More file actions
136 lines (127 loc) · 3.23 KB
/
LinkedList.java
File metadata and controls
136 lines (127 loc) · 3.23 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class linkedlist {
Node head;
int size;
linkedlist(){
this.size=0;
}
class Node{
String data;
Node next;
Node (String data){
this.data = data;
this.next = null;
size++;
}
}
// add-first
public void addFirst(String data){
Node newnode = new Node(data);
if(head==null){
head = newnode;
return;
}
newnode.next = head;
head = newnode;
}
// add-last
public void addLast(String data){
Node newNode = new Node(data);
if(head==null){
head = newNode;
return;
}
Node currentnode = head;
while(currentnode.next!=null){
currentnode = currentnode.next;
}
currentnode.next = newNode;
}
// print
public void printLinkedList(){
if(head==null){
System.out.println("empty linked list");
return;
}
Node currentnode = head;
while(currentnode!=null){
System.out.print(currentnode.data + "-->");
currentnode = currentnode.next;
}
System.out.println(" null");
}
//delete first
public void deletefirst(){
if(head==null){
System.out.println("empty");
return;
}
head = head.next;
size--;
}
//delete last
public void deletelast(){
if(head==null){
System.out.println("empty");
return;
}
if(head.next==null){
head=null;
}
Node last = head.next;
Node secondlast = head;
while(last.next!=null){
last = last.next;
secondlast = secondlast.next;
}
secondlast.next = null;
size--;
}
public void iterateList(){
if(head==null || head.next==null){
return;
}
Node prevnode = head;
Node currentnode = head.next;
while(currentnode != null){
Node nextnode = currentnode.next;
currentnode.next = prevnode;
prevnode = currentnode;
currentnode = nextnode;
}
head.next=null;
head = prevnode;
}
public Node reverseRecursive(Node head){
if(head == null || head.next == null){
return head;
}
Node newhead = reverseRecursive(head.next);
head.next.next = head;
head.next = null;
return newhead;
}
public static void main(String[] args){
linkedlist ll = new linkedlist();
ll.addFirst("c ");
ll.addFirst(" b ");
ll.addFirst(" a ");
ll.printLinkedList();
ll.addLast(" is ");
ll.addLast(" char's ");
ll.addLast(" in ");
ll.addLast(" alphabets ");
ll.printLinkedList();
ll.deletefirst();
ll.printLinkedList();
ll.deletelast();
ll.printLinkedList();
System.out.println(ll.size);
ll.addFirst("a");
ll.addLast("alphabets");
System.out.println(ll.size);
ll.iterateList();
ll.printLinkedList();
ll.head = ll.reverseRecursive(ll.head);
ll.printLinkedList();
}
}