【发布时间】:2022-01-13 06:07:21
【问题描述】:
我想为这个链表添加一个用户菜单,但是程序没有运行。
程序允许用户在当前列表的末尾添加一个节点。
在当前列表的开头添加节点。
在特定索引处添加节点。
删除给定列表中的最后一个节点并更新尾节点。
删除给定列表中的第一个节点并更新头节点。
删除给定列表中给定索引处的节点并更新头节点。
检查列表中是否存在具有给定值的节点,返回 true 或 false。
检查列表中是否存在具有给定值的节点,返回给定值的索引
列表。
我运行它时什么也没有出现。 也没有错误信息。
你如何解决这个问题?
提前谢谢你。
class Node{
int val;
int target;
int index;
Node next;
Node head;
Node tail;
public Node(int val){
this.val = val;
}
{
int choice =0;
while(choice != 9)
{
System.out.println("\n\n*********Main Menu*********\n");
System.out.println("\nChoose one option from the following list ...\n");
System.out.println("\n1.Insert node\n2.Insert at start\n3.Insert certain index\n4.Remove node");
System.out.println("\n5.Remove from the start\n6.Delete node after certain index\n7.Search for an element\n8.Search And Return Index\n9.Display nodes\n");
System.out.println("\nEnter your choice?\n");
switch(choice)
{
case 1:
addNode(val);
break;
case 2:
addNodeAtStart(val);
break;
case 3:
addNodeAtCertainIndex(val,index);
break;
case 4:
removeNode();
break;
case 5:
removeNodeAtStart();
break;
case 6:
removeNodeAtCertainIndex(index);
break;
case 7:
search(target);
break;
case 8:
searchAndReturnIndex(target);
break;
case 9:
printLinkedList();
break;
default:
System.out.println("Please enter valid choice..");
}
}
}
public void addNode(int val ){
if(head==null){
Node temp = new Node(val);
head = temp;
tail = temp;
}else{
tail.next = new Node(val);
tail = tail.next;
}
}
public void addNodeAtStart(int val ){
if(head==null){
Node temp = new Node(val);
head = temp;
tail = temp;
}else{
Node temp = new Node(val);
temp.next = head;
head = temp;
}
}
public void addNodeAtCertainIndex(int val,int index){
Node temp = head;
int count = 0;
while(temp!=null && ++count!=index)
temp = temp.next;
Node node = new Node(val);
node.next = temp.next;
temp.next = node;
}
public void removeNode(){
Node temp = head;
while(temp.next!=null && temp.next.next!=null){
temp = temp.next;
}
temp.next = null;
tail = temp;
}
public void removeNodeAtStart(){
head = head.next;
}
public void removeNodeAtCertainIndex(int index){
Node temp = head;
int count = 0;
while(temp!=null && ++count!=index)
temp = temp.next;
temp.val = temp.next.val;
temp.next = temp.next.next;
}
public boolean search(int target){
Node temp = head;
while(temp!=null){
if(temp.val == target)
return true;
}
return false;
}
public int searchAndReturnIndex(int target ){
Node temp = head;
int count = 0;
while(temp!=null){
count++;
if(temp.val==target) return count;
}
return -1;
}
public void printLinkedList(){
System.out.println();
Node temp = head;
while(temp!=null){
System.out.print(" "+temp.val);
temp = temp.next;
}
}
}
【问题讨论】:
标签: java data-structures linked-list switch-statement singly-linked-list