-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathLinkedList.java
152 lines (115 loc) · 2.23 KB
/
LinkedList.java
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
145
146
147
148
149
150
151
152
package ds_002_linkedlists;
public class LinkedList {
private Cell top;
private int size;
public LinkedList() {
size = 0;
}
public void insertAtTop(int value) {
Cell c = new Cell();
c.value = value;
c.next = top;
top = c;
size++;
}
public void insertAtIndex(int index, int value) {
if(index > this.size()) {
System.out.println("Out of list bounds!");
return;
}
if(index == 0) {
insertAtTop(value);
return;
}
Cell c = top;
for(int i = 0; c != null && (i+1)!=index; c = c.next, i++) {
;
}
Cell newCell = new Cell();
newCell.value = value;
newCell.next = c.next;
c.next = newCell;
size++;
}
public void insertAtEnd(int value) {
Cell newCell = new Cell();
newCell.value = value;
if(size == 0) {
top = newCell;
return;
}
Cell c = top;
while(c.next != null) {
c = c.next;
}
c.next = newCell;
size++;
}
public int find(int value) {
int index = 0;
for(Cell c = top; c != null; c = c.next, index++) {
if(c.value == value) {
return index;
}
}
return -1;
}
public void removeFromBeginning() {
if(this.isEmpty())
return;
top = top.next;
size--;
}
public void removeFromEnd() {
if(this.isEmpty()) {
return;
}
if(this.size == 1) {
removeFromBeginning();
}
Cell temp = top;
Cell prev = null;
while(temp.next != null) {
prev = temp;
temp = temp.next;
}
prev.next = null;
size--;
}
public void removeFromMiddle(int value) {
Cell temp = top;
Cell prev = null;
while(temp.value != value) {
prev = temp;
temp = temp.next;
}
if(prev == null) {
this.removeFromBeginning();
} else {
prev.next = temp.next;
}
size--;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void printList() {
Cell current = top;
System.out.print("List: ");
while(current != null) {
System.out.printf("%2d ", current.value);
current = current.next;
}
System.out.printf("\n");
}
public void printList2() {
System.out.print("List: ");
for(Cell current = top; current != null; current = current.next) {
System.out.printf("%2d ", current.value);
}
System.out.printf("\n");
}
}