Question
Use LinkList . Write removeLast(n) . Delete the last occurrence of an item from a linked list. So if the item is 7 and the
Use LinkList. Write removeLast(n). Delete the last occurrence of an item from a linked list. So if the item is 7 and the list is [1,3,7,4,7,3,7,2], the result is [1,3,7,4,7,3,2]
Use LinkList. Write removeAll(int n). Deletes all occurrences of an item n from a linked list. So if the item is 7 and the list1 is [1,3,7,4,7,3,2] , then list1.removeAll(7) then list1 becomes [1,3,4,3,2]. Demonstrate by displaying the list contents before and after calling the above methods. Eg:
lst1 [1,3,7,4,7,3,7,2] lst1.removelast(7) [1,3,7,4,7,3,2] lst1.removeall(7) [1,3,4,3,2]
Java Code:
public class Prog5_1 { public static void main(String[] args) { LinkList theList = new LinkList(); // make new list
theList.insertFirst(2); // insert four items theList.insertFirst(7); theList.insertFirst(3); theList.insertFirst(7); theList.insertFirst(4); theList.insertFirst(7); theList.insertFirst(3); theList.insertFirst(1);
theList.displayList(); // display list System.out.println("theList.removeLast(7)"); theList.removeLast(7); theList.displayList();
System.out.println(" theList.removeAll(7)"); theList.removeAll(7); theList.displayList(); } }
LinkList Code:
class LinkList { private Link first; // ref to first item on list // ------------------------------------------------------------- public LinkList() // constructor { first = null; } // no items on list yet // ------------------------------------------------------------- public boolean isEmpty() // true if list is empty { return (first==null); } // ------------------------------------------------------------- public void insertFirst(long dd) // insert at start of list { // make new link Link newLink = new Link(dd); newLink.next = first; // newLink --> old first first = newLink; // first --> newLink } // ------------------------------------------------------------- //public long deleteFirst() // delete first item public Link deleteFirst() // delete first item { // (assumes list not empty) Link temp = first; // save reference to link first = first.next; // delete it: first-->old next return temp; // return deleted link } // ------------------------------------------------------------- public void displayList() { System.out.print("List (first-->last): "); Link current = first; // start at beginning of list while(current != null) // until end of list, { current.displayLink(); // print data current = current.next; // move to next link } System.out.println(""); } // ------------------------------------------------------------- } // end class LinkList
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started