Skip to content

Instantly share code, notes, and snippets.

@laxmankumar2000
Created July 4, 2021 08:54
Show Gist options
  • Save laxmankumar2000/456d39e9e59b5a7d53fd5fb4f416a88e to your computer and use it in GitHub Desktop.
Save laxmankumar2000/456d39e9e59b5a7d53fd5fb4f416a88e to your computer and use it in GitHub Desktop.
Doubly
package LinkedList;
class node
{
int data;
node next;
node prev;
public node(int data)
{
this.data = data;
next = prev=null;
}
}
public class DoublyLinkedList {
node head;
node tail;
int length=0;
public DoublyLinkedList()
{
head = tail = null;
}
public boolean isEmpty()
{
if (head == null) //return length =0;
return true;
else
return false;
}
//insert
public void insert(int data)
{
node newnode = new node(data);
if (isEmpty())
{
newnode.next = head;
newnode.prev = null;
head = newnode;
tail = newnode;
}
else {
// tail.next = newnode;
// newnode.prev = tail;
// tail = newnode;
node temp = head;
while (temp.next!=null)
{
temp = temp.next;
}
temp.next= newnode;
newnode.prev = temp;
}
}
public void insertafternode(node prevnode,int data)
{
node newnode = new node(data);
newnode.next = prevnode.next;
prevnode.next = newnode;
newnode.prev = prevnode;
}
public void pint()
{
node temp =head;
node tail = null;
System.out.println("forward");
while(temp!=null)
{
System.out.print(temp.data + " ");
tail = temp;
temp=temp.next;
}
System.out.println();
System.out.println("backward");
while (tail!=null)
{
System.out.print(tail.data + " ");
tail=tail.prev;
}
}
}
class test12
{
public static void main(String[] args) {
DoublyLinkedList obj = new DoublyLinkedList();
obj.insert(10);
obj.insert(20);
obj.insert(30);
obj.insert(40);
obj.insertafternode(obj.head.next,25);
obj.pint();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment