Untitled
unknown
plain_text
a year ago
1.3 kB
4
Indexable
import java.util.*; public class LinkedList { class Node { int data; Node pre; Node next; public Node(int data) { this.data=data; } } Node head,tail=null; public void display() { Node cur=head; if(head==null) { System.out.println("List is empty"); return; } System.out.println("the doubly linked list is"); while(cur!=null) { System.out.println(cur.data+" "); cur=cur.next; } } public void addNode(int data) { Node newNode = new Node(data); if(head==null) { head=tail=newNode; head.pre=null; tail.next=null; } else { tail.next=newNode; newNode.pre=tail; tail=newNode; tail.next=null; } } public void deleteNode(int num) { Node cur,temp; if(head==null) { System.out.println("list is empty"); return; } else { cur = head; while(cur.next.data!=num) { cur=cur.next; } if(cur.next==null) { System.out.println("cannot delete"); return; } else if(cur.next.next==null) { cur.next=null; } else { temp = cur.next; cur.next=temp.next; temp.next.pre=cur; } } display(); } public static void main(String args[]) { int i,n,d,del; LinkedList ll=new LinkedList(); Scanner s= new Scanner(System.in); System.out.println("enter the number of elements"); n=s.nextInt(); System.out.println("enter the elements"); for(i=0;i<n;i++) { d=s.nextInt(); ll.addNode(d); } System.out.println("enteer the elements to be deleted"); del=s.nextInt(); ll.deleteNode(del); } }
Editor is loading...
Leave a Comment