/* Given a linked list you are to delete nodes if it has value 13 or is the 13th
ID: 3574984 • Letter: #
Question
/*
Given a linked list you are to delete nodes if it has value 13 or is the 13th node in the list.
Specifically perform deletion in the following order
1) delete all nodes that have value 13
2) if there are more than 13 elements, delete the 13th node (just once)
There can be multiple values of 13 in the linked list. Remove them all!
*/
LINKEDLIST.JAVA CLASS(GIVEN):
public class LinkedList {
public Node head;
public LinkedList() {
head = null;
}
public int size() {
if (head == null)
return 0;
int count = 1;
Node tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
count++;
}
return count;
}
public Node getHead() {
return head;
}
public void addFront(Node n) {
n.next = head;
head = n;
}
public void clear() {
head = null;
}
}
NODE.JAVA CLASS (GIVEN):
class Node {
public int value;
public Node next;
public Node() { value = 0; next = null; }
public Node(int val) { value = val; next = null; }
}
WE NEED TO DO THIS Rm13 CLASS
public class Rm13
{
public static LinkedList cleanse(LinkedList l) {
//////////////////////
// //
// your code here! //
// //
//////////////////////
}
}
Explanation / Answer
/*
Given a linked list you are to delete nodes if it has value 13 or is the 13th node in the list.
Specifically perform deletion in the following order
1) delete all nodes that have value 13
2) if there are more than 13 elements, delete the 13th node (just once)
There can be multiple values of 13 in the linked list. Remove them all!
*/
//WE NEED TO DO THIS Rm13 CLASS
public class Rm13
{
public static LinkedList cleanse(LinkedList l) {
//////////////////////
// //
// your code here! //
// //
//////////////////////
Node start = l.getHead();
int size = l.size();
if(size > 13) //If there are more than 13 nodes.
{
for(int i = 1; i < 13; i++) //Move forward 12 times, which will now point to 12th node.
start = start.next;
start.next = start.next.next; //Bypass 13th node.
size--; //Decrease size as you removed one node.
}
if(start.value == 13) //If the start node is 13, remove it.
start = start.next;
for(int i = 2; i < size; i++) //Keep moving from second node till last node.
{
if(start.next.value == 13) //If the next node value is 13.
start.next = start.next.next; //Bypass that node.
start = start.next; //Move to next node.
}
return l;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.