-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleLinkedList.java
More file actions
75 lines (67 loc) · 1.37 KB
/
Copy pathSingleLinkedList.java
File metadata and controls
75 lines (67 loc) · 1.37 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
package magicnumbers;
public class SingleLinkedList {
private Node head;
public SingleLinkedList() {
head = null;
}
public void add(Object dataToAdd) {
if (head == null) {
Node newNode = new Node(dataToAdd);
head = newNode;
} else {
Node newNode = new Node(dataToAdd);
Node temp = head;
while (temp.getLink() != null) {
temp = temp.getLink();
}
temp.setLink(newNode);
}
}
public void delete(Object dataToDelete) {
if (head == null) {
System.out.println("Linked List is empty.");
}
else {
while ((int)head.getData() == (int)dataToDelete) {
head = head.getLink();
}
Node temp = head;
Node prev = temp;
while (temp != null) {
if ((int)temp.getData() == (int)dataToDelete) {
prev.setLink(temp.getLink());
temp = prev;
}
prev = temp;
temp = temp.getLink();
}
}
}
public void display() {
if (head == null) {
System.out.print(" ");
}
else {
Node temp = head;
while (temp != null) {
System.out.print(temp.getData() + " ");
temp = temp.getLink();
}
}
}
public int size() {
int count = 0;
Node temp = head;
while (temp != null) {
count++;
temp = temp.getLink();
}
return count;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
}