情况1可以正常工作,但是情况2和3只是停止循环和程序 在那之后我无法选择其他任何情况!我不知道为什么它阻止循环继续下去,因为这里的选择永远不会等于0,我相信这是阻止循环继续前进的唯一原因!提前致谢。
我还检查了功能,所有这些对我来说似乎都很好,我不确定问题是否可能与它们有关
#include "stdafx.h"
#include <iostream>
using namespace std;
void insert_node(int new_data);
void print_node();
void delete_node();
int new_data;
char choice;
struct node {
int data;
node* next;
};
node* head = NULL;
void main()
{
do
{
cout << "Enter 1 to insert a new node \n";
cout << "Enter 2 to disply the list \n";
cout << "Enter 3 to delete the last node \n";
cin >> choice;
switch (choice)
{
case '1':
cout << "Enter the data \n";
cin >> new_data;
insert_node(new_data);
break;
case '2':
if (head != NULL)
print_node();
else
cout << "SORRY, your list is empty \n";
break;
case '3':
delete_node();
break;
default:
cout << "Invalid entry \n";
}
} while (choice != '0');
}
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
if (head == NULL)
head = NewNode;
else
{
NewNode->next = head;
head = NewNode;
}
}
void print_node()
{
node* printer=head;
do
{
cout << printer->data<<" - ";
printer = printer->next;
} while (printer != NULL);
}
void delete_node()
{
if (head == NULL)
cout << "no node to be deleted \n";
else
{
node* curr = head;
node* prev = NULL;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
if (prev == NULL)
{
delete(curr);
head = NULL;
return;
}
prev->next = NULL;
delete(curr);
}
}
答案 0 :(得分:1)
这有问题
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
if (head == NULL)
head = NewNode;
else
{
NewNode->next = head;
head = NewNode;
}
}
应该是
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
NewNode->next = head;
head = NewNode;
}
将第一个节点添加到列表时,您的版本无法设置next
。如您所见,无需将head == NULL
设为特例。
由于您首先没有正确创建列表,因此任何尝试从列表中打印或删除项目的尝试都可能会失败。
并且您的print_node
函数在空白列表上将失败。应该是while循环,而不是do ... while循环。
void print_node()
{
node* printer=head;
while (printer != NULL)
{
cout << printer->data<<" - ";
printer = printer->next;
}
}
您的delete_node
函数对我来说也非常可疑。