-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintDoubleLinkedListBackward.java
More file actions
118 lines (102 loc) · 2.98 KB
/
Copy pathPrintDoubleLinkedListBackward.java
File metadata and controls
118 lines (102 loc) · 2.98 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
109
110
111
112
113
114
115
116
117
118
/*
* Author : Hasnain Memon
* Date : 20/11/2024
*/
public class PrintDoubleLinkedListBackward {
Node head;
Node tail;
static class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
next = null;
prev = null;
}
}
// Task 1: Write a Java program to traverse a doubly linked list (backward). Starting from tail.
public void printListBackward() {
Node current = tail;
System.out.print("null <-> ");
while (current != head) {
System.out.print(current.data + " <-> ");
current = current.prev;
}
System.out.println(current.data + "");
}
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
return;
}
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " <-> ");
current = current.next;
}
System.out.println("null");
}
public void insertAtStart(int data) {
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
return;
}
head.prev = newNode;
newNode.next = head;
head = newNode;
}
public void insertAfter(Node prevNode, int data) {
if (prevNode == null) {
System.out.println("Given previous node can't be null");
return;
}
Node newNode = new Node(data);
Node temp = prevNode.next;
prevNode.next = newNode;
newNode.prev = prevNode;
newNode.next = temp;
if (temp != null) {
temp.prev = newNode;
}
}
public void deleteFirst() {
if (head == null) {
System.out.println("List is empty!");
return;
}
head = head.next;
}
public void deleteAtPosition(int position) {
if (head == null) {
System.out.println("List is empty!");
return;
}
Node current = head;
for (int i = 0; i < position - 1; i++) {
current = current.next;
}
if (current == null || current.next == null) {
System.out.println("Position out of bounds!");
return;
}
current.next = current.next.next;
}
public static void main(String[] args) {
PrintDoubleLinkedListBackward list = new PrintDoubleLinkedListBackward();
list.insertAtEnd(10);
list.insertAtEnd(30);
list.insertAtEnd(50);
list.insertAtEnd(20);
list.insertAtEnd(60);
list.printList();
list.printListBackward();
}
}