/
LinkedList.java
91 lines (83 loc) · 1.76 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
package ds;
public class LinkedList {
public ListNode head;
public LinkedList () {
head = null;
}
/*
* Implement the LIST-SEARCH(L, k) function
*/
public ListNode search (int k) {
ListNode start = head;
if(this.head == null)
return this.head;
while (start != null) {
if(start.key == k) {
return start;
}
start = start.next;
}
return null;
}
/*
* Implement the LIST-INSERT(L, x) function
* Note that x is a integer value, not a ListNode
*/
public void insert (int x) {
ListNode tempNode = new ListNode(x);
tempNode.next = this.head;
tempNode.prev = null;
if(this.head != null)
this.head.prev = tempNode;
this.head = tempNode;
}
/*
* Implement the LIST-DELETE(L, x) function
*/
public void delete (ListNode x) {
ListNode start = head;
if(this.head == null) {
System.out.println("Linked list is empty");
}
else {
while(start != null && start != x) {
start = start.next;
}
if (start == x) {
ListNode prevNode = x.prev;
ListNode nextNode = x.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
}
}
}
/*
* Convert a LinkedList to a string in the format of [#elements]
*/
public String toString () {
String str;
ListNode x;
str = "[";
x = this.head;
while (x != null) {
str += x.key + ",";
x = x.next;
}
str += "]";
return str;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList l;
l = new LinkedList();
for (int i = 0; i < 5; i++)
l.insert(i);
System.out.println(l.toString());
for (int i = 0; i < 2; i++)
l.delete(l.head.next);
System.out.println(l.toString());
}
}