-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinkedlist.java
More file actions
144 lines (122 loc) · 2.66 KB
/
linkedlist.java
File metadata and controls
144 lines (122 loc) · 2.66 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
137
138
139
140
141
142
143
144
package selfpractice;
import java.util.Scanner;
public class linkedlist {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
addlastLL st= new addlastLL();
while(n-->0){
int a = s.nextInt();
st.addlast(a);
}
int x = s.nextInt();
while(x-->0)
{
int i = s.nextInt();
st.removeat(i);
}
st.display();
}
public static class addlastLL {
private class Node {
int data;
Node next;
}
Node head;
Node tail;
int size;
public void addlast(int val)// o(1)
{
if (this.size == 0) {
handleaddwhensize0(val);
return;
}
Node node = new Node();
node.data = val;
tail.next = node;
tail = node;
size++;
}
private void handleaddwhensize0(int val) {
Node node = new Node();
node.data = val;
head = node;
tail = node;
size++;
}
public int removefirst() {
if (size == 0) {
// System.out.println("list empty");
return -1;
} else if (size == 1) {
int x = handlewhensize1();
return x;
}
int rv = head.data;
Node second = head.next;
head = second;
size--;
return rv;
}
public int removelast()// o(n)
{
if (size == 0) {
// System.out.println("list empty");
return -1;
} else if (size == 1) {
int x = handlewhensize1();
return x;
}
int rv = tail.data;
Node secondlast = getNodeAt(size - 2);
tail = secondlast;
tail.next = null;
size--;
return rv;
}
private int handlewhensize1() {
int rv = head.data;
head = tail = null;
size = 0;
return rv;
}
public void display()// o(n)
{
for (Node node = head; node != null; node = node.next) {
System.out.print(node.data + " ");
}
}
public int removeat(int idx) {
if (idx < 0 || idx >= size) {
// System.out.println("linked list out of bound");
return -1;
} else if (idx == 0) {
return this.removefirst();
} else if (idx == size - 1) {
return this.removelast();
}
Node nm1 = getNodeAt(idx - 1);
Node n = nm1.next;
Node np1 = n.next;
int rv = n.data;
nm1.next = np1;
size--;
return rv;
}
private Node getNodeAt(int idx){
if (size == 0){
// System.out.println("list is empty");
return null;
}else if (idx < 0 || idx >= size){
// System.out.println("index out of bound");
return null;
}
Node node = head;
for (int i = 0; i < idx; i++){
node = node.next;
}
return node;
}
}
}