-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathLinkedList.java
More file actions
93 lines (78 loc) · 2.15 KB
/
LinkedList.java
File metadata and controls
93 lines (78 loc) · 2.15 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
import java.lang.*;
public class List {
class Node {
int key;
Node next;
public Node (int key){
this.key = key;
}
public void print() {
System.out.println ("Key: " + key);
System.out.println ("Next: " + next);
}
}
Node head;
public List (Node head){
this.head = head;
}
public boolean isEmpty(){
return head.next == null;
}
public boolean exists (int key) {
Node current = head;
while (current != null){
if (current.key == key) return true;
current = current.next;
}
return false;
}
public void insertAtHead (Node toInsert){
toInsert.next = head.next;
head.next = toInsert;
}
public void insertAtTail (Node toInsert){
Node current = head;
while (current.next != null){
current = current.next;
}
current.next = toInsert;
toInsert.next = null;
}
public void insertAfterKey (int key, Node toInsert){
Node current = head;
if (!exists(key)) System.out.println ("Key not found.");
else {
while (current.key != key){
current = current.next;
}
toInsert.next = current.next;
current.next = toInsert;
}
}
public Node getElement(int pos){
Node current = head;
for (int i = 1; i <= pos; i++){
current = current.next;
}
return current;
}
public int countElements (){
Node current = head;
int counter = 0;
while (current != null){
counter++;
current = current.next;
}
return counter;
}
public void printList (){
Node current = head;
while (current != null){
System.out.println ("Key: " + current.key);
if (current.next == null) System.out.println ("Last Node.");
else System.out.println ("Next: " + current.next.key);
current = current.next;
}
System.out.print (countElements() + " Elements in this List.");
}
}