Repository navigation
Expand file tree
/
Copy pathLinkedListExample.java
More file actions
87 lines (72 loc) · 1.96 KB
/
Copy pathLinkedListExample.java
File metadata and controls
87 lines (72 loc) · 1.96 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
package org.group_id_amit.dsa;
class Node{
int val;
Node prev;
Node next;
Node(int val, Node prev, Node next){
this.val = val;
this.prev = prev;
this.next = next;
}
Node(int val){
this(val, null, null);
}
}
class CustomLinkedList{
private Node dummyHead;
private Node dummyTail;
private int size; // Number of elements in the list
// constructor
public CustomLinkedList(){
dummyHead = new Node(-1);
dummyTail = new Node(-1);
dummyHead.next = dummyTail;
dummyTail.prev = dummyHead;
size = 0;
}
// Add a node to the end of the list
public void add(int data){
Node node = new Node(data);
Node tail = dummyTail.prev;
tail.next = node;
node.prev = tail;
node.next = dummyTail;
dummyTail.prev = node;
size++;
}
// remove the first occurrence of a node with the given data
public boolean remove(int data) {
Node current = dummyHead.next;
while(current!=null){
if(current.val == data){
Node prev = current.prev;
Node next = current.next;
prev.next = next;
next.prev = prev;
size--;
return true;
}
current = current.next;
}
return false;
}
public void displayForward(){
Node current = dummyHead.next;
while(current != dummyTail){
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("null");
}
}
public class LinkedListExample {
public static void main(String[] args){
CustomLinkedList customLinkedList = new CustomLinkedList();
customLinkedList.add(10);
customLinkedList.add(20);
customLinkedList.add(40);
customLinkedList.add(60);
customLinkedList.add(70);
customLinkedList.displayForward();
}
}