-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDoublyLinkedListImpl.java
executable file
·162 lines (133 loc) · 3.55 KB
/
DoublyLinkedListImpl.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
153
154
155
156
157
158
159
160
161
162
package sa.edu.yuc;
import java.util.Iterator;
public class DoublyLinkedListImpl<T extends Comparable<T>> implements DoublyLinkedList<T> {
private Node head=null;
private Node tail=null;
private int size ;
public class Node{
private Node next;
private Node prev;
private T data;
public Node(T data) {
this.data = data;
}
}
@Override
public boolean isEmpty() {
if (head==null) {
return true;
}
return false;
}
@Override
public boolean insertFirst(T item) {
Node nod = new Node(item);
nod.next=head;
head.prev=nod;
nod.prev=null;
head=nod;
size++;
return true;
}
@Override
public boolean insertLast(T item) {
Node nod = new Node(item);
nod.prev=tail;
tail.next=nod;
nod.next=null;
tail=nod;
size++;
return true;
}
@Override
public T removeFirst() {
T b=head.data;
Node nod=head;
head.next=nod;
nod.prev=null;
size--;
return b;
}
@Override
public T removeLast() {
T b = tail.data;
Node temp=tail;
tail=temp.prev;
tail.next=null;
size--;
return b;
}
@Override
public boolean insertAtPosition(int position, T item) {
Node nod = new Node(item);
Node temp=head;
if (size>position) {
for (int i = 2; i < position; i++)
temp=temp.next;
}
nod.prev=temp;
nod.next=temp.next;
temp.next=nod;
temp.next.prev=nod;
size++;
return true;
}
@Override
public T removeAtPosition(int position) {
Node temp=head;
if (size>position) {
for (int i = 2; i < position; i++)
temp=temp.next;
}
T b=temp.data;
temp.next=temp.next.next;
temp.prev=null;
return b;
}
@Override
public T search(T item) {
Node temp=head;
while(temp!=null){
if (temp.data==item)
return temp.data;
temp=temp.next;
}
return null;
}
@Override
public T getFirst() {
return head.data;
}
@Override
public int getPosition(T item) {
int pos=1;
Node temp=head;
while (temp!=null){
if (temp.data == item)
return pos;
pos++;
temp=temp.next;
}
return -1;
}
@Override
public T removeValue(T item) {
Node current=head;
Node temp=null;
while (current !=null && current.data != item)
if (current.data == item) {
temp=current;
current= current.next;
}
temp.next=current.next;
return current.data;
}
public String toString(){
String temp="";
Node current = head;
while (current != null)
temp+= current.data+"\n";
current=current.next;
return temp;
}
}