-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoublyLinkedList.java
More file actions
108 lines (94 loc) · 2.71 KB
/
DoublyLinkedList.java
File metadata and controls
108 lines (94 loc) · 2.71 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
public class DoublyLinkedList{
private class LinkedNode{
private int payload;
private LinkedNode next;
private LinkedNode previous;
private LinkedNode(int payload,LinkedNode previous,LinkedNode next){
this.payload=payload;
this.previous=previous;
this.next=next;
}
private int getPayload(){return payload;}
}
private LinkedNode head;
private int size=0;
private DoublyLinkedList(LinkedNode head){this.head=head;}
public DoublyLinkedList(){this(null);}
private void add(LinkedNode node){
if (head==null){
head=node;
return;
}
LinkedNode currentNode = head;
while (currentNode.next!=null){
currentNode=currentNode.next;
}
currentNode.next=node;
node.previous=currentNode;
size++;
}
public void add(int payload){this.add(new LinkedNode(payload,null,null));}
public String toString(){
String result=new String();
LinkedNode currentNode = head;
while (currentNode!=null){
result+=currentNode.getPayload()+" ";
currentNode=currentNode.next;
}
return result;
}
public boolean exists(int payload){
LinkedNode currentNode = head;
while(currentNode!=null){
if (currentNode.getPayload()==payload) return true;
currentNode=currentNode.next;
}
return false;
}
public int getSize(){return size;}
public boolean delete(int payload){
if (head==null) return false;
else if (head.getPayload()==payload){
head=head.next;
head.previous=null;
size--;
return true;
}
LinkedNode currentNode=head;
while (currentNode.next!=null){
if (currentNode.next.getPayload()==payload){
LinkedNode newNext=currentNode.next.next;
currentNode.next=newNext;
newNext.previous=currentNode;
size--;
return true;
}
currentNode=currentNode.next;
}
return false;
}
public void reverse(){
LinkedNode currentNode=head;
if (currentNode==null) return;
while (currentNode.next!=null){
LinkedNode temp=currentNode.next;
currentNode.next=currentNode.previous;
currentNode.previous=temp;
currentNode=currentNode.previous;
}
LinkedNode temp=currentNode.next;
currentNode.next=currentNode.previous;
currentNode.previous=temp;
head=currentNode;
//System.out.println(head.next.getPayload());
}
public static void main(String[] args){
DoublyLinkedList list=new DoublyLinkedList();
list.add(3);
list.add(5);list.add(13);list.add(35);list.add(83);list.add(23);
System.out.println(list.toString());
list.reverse();
System.out.println(list.toString());
System.out.println(list.exists(3));
}
}