top of page
Search
Writer's pictureAbhinaw Tripathi

Continuing on Linked Lists(Finding and Deleting Specified Links)


Finding and Deleting Specified Links: Search a linked list for a data item with a specified key value and to delete an item with a specified key value.These along with insertion at the start of the list are the same operations carried out by the Link List workshop.follow the below sample code. Work Shop with Code: /** * @author Abhinaw.Tripathi * */ class Link { public int idata; public double dData; public Link next; public Link(int id,double dd) { this.idata=id; this.dData=dd; } public void displayLink() { System.out.println(" { " +idata + "," +dData + "} "); } } class LinkList { private Link first; public LinkList() { first=null; } public void insertFirst(int id,double dd) { Link newLink=new Link(id, dd); newLink.next=first; first=newLink; } public Link find(int key) { Link current=first; while(current.idata!=key) { if(current.next == null) return null; else current=current.next; } return current; } public Link delete(int key) { Link current=first; Link previous=first; while(current.idata!=key) { if(current.next==null) return null; else { previous=current; current=current.next; } } if(current == first) first=first.next; else previous.next=current.next; return current; } public void displayList() { System.out.println("First----->Last : "); Link current=first; while(current!=null) { current.displayLink(); current=current.next; } System.out.println(" "); } } public class LinkListApp { /** * */ public LinkListApp() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub LinkList theList=new LinkList(); theList.insertFirst(22, 2.99); theList.insertFirst(44, 8.99); theList.insertFirst(66, 4.99); theList.insertFirst(88, 6.99); theList.displayList(); Link f=theList.find(44); if(f!=null) System.out.println("Found link with key " + f.idata); else System.out.println("Can't find the link"); Link d=theList.delete(66); if(d!=null) System.out.println("Deletd link with the key " +d.idata); else System.out.println("Cant delete link"); theList.displayList(); } }

The desire output will be like this First----->Last : { 88,6.99} { 66,4.99} { 44,8.99} { 22,2.99} Found link with key 44 Deletd link with the key 66 First----->Last : { 88,6.99} { 44,8.99} { 22,2.99}

2 views0 comments

Recent Posts

See All
bottom of page