Assignment
University
California State UniversityCourse
COMP 182 | Data Structures and Program Design and LabPages
4
Academic year
2023
KauK
Views
14
ShoppingList.java import java . util .*; public class ShoppingList { public static void main ( String [] args ) { Scanner scnr = new Scanner ( System . in ); // TODO: prompt the user to enter the items ItemNode headNode ; // Create intNode objects ItemNode currNode ; ItemNode lastNode ; String item ; int i ; // Front of nodes list headNode = new ItemNode (); lastNode = headNode ; System . out . print ( "Enter a number to indicate how many items you will enter: " ); int input = scnr . nextInt (); System . out . println (); System . out . print ( "Please enter your items separated by space: " ); for ( i = 0 ; i < input ; i ++ ){ item = scnr . next (); currNode = new ItemNode ( item ); lastNode . insertAtEnd ( headNode , currNode ); lastNode = currNode ; } // Print linked list currNode = headNode . getNext (); while ( currNode != null ) { currNode . printNodeData (); currNode = currNode . getNext (); } } } ItemNode.java public class ItemNode { private String item ; private ItemNode nextNodeRef ; // Reference to the next node public ItemNode () { item = "" ; nextNodeRef = null ; } // Constructor public ItemNode ( String itemInit ) {
this . item = itemInit ; this . nextNodeRef = null ; } // Constructor public ItemNode ( String itemInit , ItemNode nextLoc ) { this . item = itemInit ; this . nextNodeRef = nextLoc ; } // Insert node after this node. public void insertAfter ( ItemNode nodeLoc ) { ItemNode tmpNext ; tmpNext = this . nextNodeRef ; this . nextNodeRef = nodeLoc ; nodeLoc . nextNodeRef = tmpNext ; } // TODO: Define insertAtEnd() method that inserts a node // to the end of the linked list public void insertAtEnd ( ItemNode headNode , ItemNode newNode ) { //if list is empty, add the new node to the head if ( headNode . nextNodeRef == null ) { headNode . nextNodeRef = newNode ; } else { //traverse to the end of the list, and add the new node ItemNode currNode = headNode ; while ( currNode . nextNodeRef != null ) { currNode = currNode . nextNodeRef ; } currNode . nextNodeRef = newNode ; } } // Get location pointed by nextNodeRef public ItemNode getNext () { return this . nextNodeRef ; } public void printNodeData () { System . out . println ( this . item ); } }
COMP 182: Lab Assignment 5 - Shopping List
Please or to post comments