Question: I have implemented a String linked list in java below. I need a delete method that updates the index variable of the list named lineNumber.

I have implemented a String linked list in java below. I need a delete method that updates the index variable of the list named lineNumber. Whenever an item is removed from the list, the index for all the other lineNumbers need to be updated as well. All lines after the line removed are then numbered one less than their previous number. My code so far can be found below:

public class List { private Node head; public List() { head = null; } public void print() { if (head != null) { head.print(); } } public void add ( String data ) { if (isEmpty()) head = new Node(data, head,0); else{ int count = head.getLineNum() + 1; head = new Node(data,head,count); } } /*public void add ( String data ) { head = new Node(data, head); }*/ public boolean find(String key) { Node current = head; //Initialize current while (current != null) { if (current.getData().equals(key)) return true; //data found current = current.getNext(); } return false; } public void replaceContent(int lineNum, String newContent) { Node temp = head; while(temp!=null && temp.getLineNum()!=lineNum) { temp = temp.getNext(); } if(temp==null) { System.out.println("Line number invalid"); } else { temp.setData(newContent); } } public void remove(int key){ Node current = head; // search for link Node previous = head; while(current.getLineNum() != key) { if (current.getNext() == null) System.out.println("Line number is not valid"); else { previous = current; current = current.getNext(); } } if(current == head) head = head.getNext(); else previous.setNext(current.getNext()); } public boolean isEmpty(){ return head == null; } public Node getHead() { return head; } }
public class Node { private String data; //private ListItem data; private Node next; private int lineNum; public Node(String data, Node next, int lineNum) { this.data = data; this.next = next; this.lineNum = lineNum; } public Node(String data, Node next) { this.data = data; this.next = next; } public void print() { System.out.println(lineNum+ " " +data); if (next != null) next.print(); } public String getData() { return data; } public Node getNext() { return next; } public void setLineNum(int lineNum) { this.lineNum = lineNum; } public int getLineNum() { return lineNum; } public void setData(String data) { this.data = data; } public void setNext(Node next) { this.next = next; } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!