Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create doubly linked list #4759

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Java/doubly linked list
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
class Node {
int data;
Node prev, next;
Node(int data) {
this.data = data;
prev = next = null;
}
}

class DoublyLinkedList {
Node head;

DoublyLinkedList() {
head = null;
}

void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.prev = temp;
}

void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}

void delete(int data) {
if (head == null) return;
Node temp = head;
while (temp != null && temp.data != data) {
temp = temp.next;
}
if (temp == null) return;
if (temp == head) head = temp.next;
if (temp.next != null) temp.next.prev = temp.prev;
if (temp.prev != null) temp.prev.next = temp.next;
temp = null;
}
}

public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.insertAtEnd(10);
list.insertAtEnd(20);
list.insertAtEnd(30);
list.insertAtEnd(40);
list.display();
list.delete(20);
list.display();
}
}