【发布时间】:2021-05-27 16:09:39
【问题描述】:
下面是一个用于插入链表的简单程序,但是,每当我运行该程序时,它只会读取列表的两个输入值并停止进一步执行。这是为什么?我无法发现问题。
/**** Defining structure of node *****/
class Node{
public:
int data;
Node* next;
Node(int val){
data = val;
next = NULL;
}
};
/**** Inserting node at the end ****/
Node* insertAtEnd(Node* &head, int val){
Node* n = new Node(val);
if(head == NULL){
head = n;
}
Node* tmp = head;
while(tmp->next != NULL){
tmp = tmp->next;
}
tmp->next = n;
return tmp;
}
/**** Menu ****/
int menu(){
int ch;
cout<<"1. Insert node"<<endl;
cout<<"Enter your choice: ";
cin>>ch;
cout<<endl;
return(ch);
}
/**** Driver Code ****/
int main(){
Node* head = NULL; int n, data;
switch(menu()){
case 1:
cout<<"\nEnter number of nodes you want to enter: ";
cin>>n;
for(int i = 0; i<n; i++){
cout<<"Enter data: ";
cin>>data;
insertAtEnd(head, data);
}
break;
default:
cout<<"Wrong Choice";
}
}
【问题讨论】:
-
您的 InsertAtEndFunction 似乎无法正确处理 head 为 NULL 的情况。您将得到一个列表,其中 head->next == head。
-
当 C++ 是语言时,人们需要停止教授 C 风格的链表。
-
您应该维护一个指向列表中最后一个节点的指针。这将使在列表末尾插入更有效。
-
@SvenNilsson 是的,我应该在 head = n; 之后添加 return非常感谢
-
还要检查是否需要在insertAtEnd函数中返回
temp或head
标签: c++ data-structures singly-linked-list