-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkList.java
More file actions
108 lines (97 loc) · 2.57 KB
/
LinkList.java
File metadata and controls
108 lines (97 loc) · 2.57 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
class LinkedList<T>{
class Link<T>{
T data;
Link next;
Link previous;
public Link(T data){
this.data = data;
}
public void displayLink(){
if(this == first)
System.out.print("First --> ");
System.out.print(data);
if(this.next != null)
System.out.print(" -> ");
if(this == last)
System.out.print(" <-- Last\n");
}
}
Link first;
Link last;
public boolean isEmpty(){
return first == null;
}
public Link find(T data){
if (isEmpty())
return null;
Link current = first;
while(current != null && current.data != data){
current = current.next;
}
return current;
}
public void insertFirst(T data){
Link newLink = new Link(data);
if(isEmpty())
last = newLink;
else
first.previous = newLink;
newLink.next = first;
first = newLink;
}
public void insertLast(T data){
Link newLink = new Link(data);
if(isEmpty())
first = newLink;
else
last.next = newLink;
newLink.previous = last;
last = newLink;
}
public void insertAfter(Link previousLink,T data){
Link newLink = new Link(data);
if(isEmpty()){
insertFirst(data);
return;
}
if(previousLink == last){
last = newLink;
}else{
newLink.next = previousLink.next;
previousLink.next.previous = newLink;
}
newLink.previous = previousLink;
previousLink.next = newLink;
}
public void insertBefore(Link nextLink,T data){
Link newLink = new Link(data);
if(isEmpty() || nextLink == first){
insertFirst(data);
return;
}
newLink.next = nextLink;
newLink.previous= nextLink.previous;
nextLink.previous.next=newLink;
nextLink.previous = newLink;
}
public Link delete(Link Target){
if(Target == first){
first = Target.next;
}else{
Target.previous.next = Target.next;
}
if(Target == last){
last = Target.previous;
}else{
Target.next.previous = Target.previous;
}
return Target;
}
public void displayList(){
Link current = first;
while(current != null){
current.displayLink();
current = current.next;
}
}
}