问题描述
下面是一个用于插入链表的简单程序,但是,每当我运行该程序时,它只读取列表的两个输入值并停止进一步执行。这是为什么?我无法发现问题。
/**** 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";
}
}
解决方法
insertAtEnd
需要提前返回第一个节点,否则会陷入无限循环。
Node* insertAtEnd(int val) {
Node* n = new Node(val);
if (head == NULL) {
head = n;
return head;
}
Node* tmp = head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = n;
return tmp;
}
你的代码大部分是c风格的,没有处理内存释放,所以内存泄漏了。
我添加了 list
类以使其在 C++ 中更自然,添加使用析构函数来释放动态内存。
struct List {
Node* head = nullptr;
Node* insertAtEnd(int val) {
Node* n = new Node(val);
if (head == NULL) {
head = n;
return head;
}
Node* tmp = head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = n;
return tmp;
}
~List() {
while (head) {
auto tmp = head->next;
delete head;
head = tmp;
}
}
};
,
在List末尾的函数add Node中,我认为你应该传值指针“Node* head”不通过引用传递“Node*& head” ”。 我实际上是这样编码的,我的代码运行正确,没有任何错误。你可以参考我下面的代码
Node* addtail(Node* head,int value) { //
Node* p;
Node* temp = new Node;
temp->data = value;
temp->next = NULL;
if (head == NULL) { // if head empty => head = temp instantly
head = temp;
}
else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
return head;
}