【发布时间】:2022-11-03 13:18:50
【问题描述】:
我正在为 java 类开发一个实验室。以下是给出的方向和代码: 给定 ShoppingList 类中的 main(),在 ItemNode 类中定义一个 insertAtEnd() 方法,该方法将元素添加到链表的末尾。不要打印虚拟头节点。
前任。如果输入是:
4 羽衣甘蓝 生菜 萝卜 花生 其中 4 是要插入的项目数; Kale, Lettuce, Carrots, Peanuts 是要添加到列表末尾的项目的名称。
输出是:
羽衣甘蓝 生菜 萝卜 花生
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
// Get location pointed by nextNodeRef
public ItemNode getNext() {
return this.nextNodeRef;
}
public void printNodeData() {
System.out.println(this.item);
}
}
这也是其中的一部分,但是这段代码不能编辑:
import java.util.Scanner;
public class ShoppingList {
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
ItemNode headNode; // Create intNode objects
ItemNode currNode;
ItemNode lastNode;
String item;
int i;
// Front of nodes list
headNode = new ItemNode();
lastNode = headNode;
int input = scnr.nextInt();
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();
}
}
}
这就是我所拥有的,但代码没有以正确的顺序给出输出。谁能帮我理解我需要改变什么,好吗?
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 currNode){
currNode.nextNodeRef = headNode.nextNodeRef;
headNode.nextNodeRef = currNode;
// Get location pointed by nextNodeRef
public ItemNode getNext() {
return this.nextNodeRef;
}
public void printNodeData() {
System.out.println(this.item);
}
}
【问题讨论】:
标签: java