-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoubleLinklist.java
More file actions
106 lines (104 loc) · 2.97 KB
/
Copy pathDoubleLinklist.java
File metadata and controls
106 lines (104 loc) · 2.97 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
public class DoubleLinklist {
class Node {
String data;
Node next;
Node prev;
public Node(String data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private Node head;
private Node tail;
public void AddFirst(String data) {
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
}
else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
public void AddLast(String data) {
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
}
else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public boolean insert(String data, int index) {
if (index < 0 || index > data.length()) {
System.out.println("Invalid index");
return false;
}
if (index == 0) {
AddFirst(data);
return true;
}
Node newNode = new Node(data);
Node current = head;
int currentIndex = 0;
while (current != null && currentIndex < index - 1) {
current = current.next;
currentIndex++;
}
if (current == null) {
return false;
}
newNode.next = current.next;
if (current.next != null) {
current.next.prev = newNode;
}
current.next = newNode;
newNode.prev = current;
if(newNode.next == null){
tail = newNode;
}
return true;
}
public void remove(String value) {
if (head == null) return;
Node current = head;
while (current != null) {
if (current.data.equals(value)) {
if (current == head) {
head = head.next;
if (head != null) head.prev = null;
} else if (current == tail) {
tail = tail.prev;
if (tail != null) tail.next = null;
} else {
current.prev.next = current.next;
current.next.prev = current.prev;
}
System.out.println("Елемент '" + value + "' видалено.");
return;
}
current = current.next;
}
System.out.println("Елемент '" + value + "' не знайдено.");
}
public void showFromStart(){
Node current = head;
while (current != null) {
System.out.println(current.data + " ");
current = current.next;
}
System.out.println();
}
public void showFromEnd(){
Node current = tail;
while (current != null) {
System.out.println(current.data + " ");
current = current.prev;
}
System.out.println();
}
}