我正在做一个在链表的特定位置插入节点的功能。
除了选项 5) 在特定位置插入和 9) 显示之外,一切都运行良好。
如果我选择 5),程序会要求输入一个数字。提供数字后,它会自行终止。
同样,当我选择9)时,程序会显示节点中的数据然后终止,但我已经放入了一个
while
循环来停止。
我的主文件:
#include <iostream>
using namespace std;
int value, count, value2, count2;
struct node
{
int data;
node * next;
};
node *list = nullptr;
node * p;
node * q;
node * r;
void insertFront()
{
cout << "ENTER A VALUE=";
cin >> value;
if (list == nullptr)
{
p = new node();
p->data = value;
p->next = nullptr;
list = p;
}
else
{
p = new node();
p->data = value;
p->next = list;
list = p;
}
}
void display()
{
p = list;
while (p != nullptr)
{
cout << p->data << " ";
p = p->next;
}
cout << p->data << endl;
}
void insertSpec()
{
cout << "Enter the number after which you want to enter a node=";
cin >> value;
if (list == nullptr && value > 1)
{
cout << "THERE IS NO OTHER NODE SO YOU CANNOT PUT A NODE AT " << value;
}
if (list != nullptr && value > 0)
{
cout << "ENTER THE NUMBER YOU WANT TO ENTER=";
cin >> value2;
count = 1;
count2 = 1;
while (count != (value))
{
p = p->next;
count++;
}
while (count2 != (value + 1))
{
q = q->next;
count2++;
}
r = new node();
r->data = value2;
p->next = r;
r->next = q;
}
}
int main()
{
int choice;
cout << "1) Insert at front" << endl;
cout << "5) Insert at specified place" << endl;
cout << "9) Display" << endl << endl;
while (choice != 99)
{
cout << "Your choice:";
cin >> choice;
switch (choice)
{
case 1:
{
insertFront();
break;
}
case 5:
{
insertSpec();
break;
}
case 9:
{
display();
break;
}
case 99:
{
cout << "PROGRAM TERMINATED :)";
break;
}
}
}
return 0;
}
在
insertSpec()
中,如果用户指定的节点号超过列表末尾,则第一个循环具有未定义的行为,第二个循环具有未定义的行为,因为q
从未被分配指向有效的 node
.
display()
在循环结束后尝试访问 p->data
时有 undefined behavior因为
p
到那时是 nullptr
.
尝试更像这样的东西:
#include <iostream>
using namespace std;
struct node
{
int data;
node *next = nullptr;
};
node *list = nullptr;
void insertFront()
{
int value;
cout << "ENTER A VALUE=";
cin >> value;
list = new node{value, list};
}
void display()
{
for(node *p = list; p != nullptr; p = p->next)
{
cout << p->data << " ";
}
cout << endl;
}
void insertSpec()
{
int number, value;
cout << "Enter the node number after which you want to enter a new node=";
cin >> number;
if (number < 1)
{
cout << "INVALID NODE NUMBER!" << endl;
return;
}
node **p = &list;
int n = number;
while (*p != nullptr && n > 0)
{
p = &((*p)->next);
--n;
}
if (n > 0)
{
cout << "YOU CANNOT PUT A NODE AFTER " << number << endl;
return;
}
cout << "ENTER THE VALUE YOU WANT TO ADD=";
cin >> value;
*p = new node{value, *p};
}
int main()
{
int choice;
cout << "1) Insert at front" << endl;
cout << "5) Insert at specified place" << endl;
cout << "9) Display" << endl;
cout << "99) Exit" << endl << endl;
do
{
cout << "Your choice:";
cin >> choice;
switch (choice)
{
case 1:
insertFront();
break;
case 5:
insertSpec();
break;
case 9:
display();
break;
}
}
while (choice != 99);
cout << "PROGRAM TERMINATED :)";
return 0;
}