Make a method that removes and returns the last value from the LinkedList. Call this method: remove
Question:
Make a method that removes and returns the last value from the LinkedList. Call this method: remove
a. Parameter(s): a LinkedList b. Returns: an Integer c. Ex. Input (as LinkedList elements): [5,8,6,0]. Output: 0. LinkedList after method
call: [5,8,6].
Main Method:
class Main { public static void main(String[] args) { System.out.println("Hello world!"); LUCLinkedList list = new LUCLinkedList(); list = LUCLinkedList.insert(list, 5); list = LUCLinkedList.insert(list, 8); list = LUCLinkedList.insert(list, 6); list = LUCLinkedList.insert(list, 0);
System.out.println(LUCLinkedList.printList(list)); System.out.println(LUCLinkedList.remove(list)); System.out.println(LUCLinkedList.printList(list)); } }
Insert remove method here:
import java.io.*;
public class LUCLinkedList {// a Singly Linked List Node head; // head of list public static LUCLinkedList insert(LUCLinkedList list, int data) // Method to insert a new node { Node new_node = new Node(data); // Create a new node with given data new_node.next = null; if (list.head == null) { // If the Linked List is empty, then make the new node as head list.head = new_node; } else {// Else traverse till the last node and insert the new_node there Node last = list.head; while (last.next != null) { last = last.next; } last.next = new_node; // Insert the new_node at last node } return list; }
//updated method to return string instead of void public static String printList(LUCLinkedList list) // Method to print the LinkedList. { String s = "LinkedList: "; Node currNode = list.head; while (currNode != null) { // Traverse through the LinkedList s += currNode.data + " "; //System.out.print(currNode.data + " "); // Print the data at current node currNode = currNode.next; // Go to next node } return s.trim(); }
//Add code here
}
Resources:
- https://www.youtube.com/watch?v=ku5TRGICifA
- https://www.youtube.com/watch?v=mOMSPOeTzTY
- https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/LinkedList.html
Building Java Programs A Back To Basics Approach
ISBN: 9780135471944
5th Edition
Authors: Stuart Reges, Marty Stepp