【发布时间】:2018-11-03 20:36:29
【问题描述】:
我正在编写一个程序,它需要 8 个用户输入的整数并从中创建一个链表。我让程序打印链接列表,然后删除最后一个节点并反向打印列表。在此过程中,我一直在测试程序以确保每个部分都能正常工作,并且一直到打印出原始链接列表的地步。
当我写完修改代码然后打印部分时,我遇到了一个问题——打印出原始列表后程序不会输出任何内容。例如,如果我输入 1,2,3,4,5,6,7,8,它将输出: 1 2 3 4 5 6 7 8 就是这样。我试过把 cout
我不确定为什么 while 循环会导致程序直接停止输出任何内容,甚至是与 while 循环本身无关的任意 cout 语句,所以我想我会在这里问。如果有帮助,我正在使用 Visual Studio 2017。感谢您的所有帮助!
#include <iostream>
using namespace std;
void getdata(int & info); //function that assigns a user inputted value to each node
const int nil = 0;
class node_type // declaration of class
{
public:
int info;
node_type *next;
};
int main()
{
node_type *first, *p, *q, *r, *newnode;
first = new node_type;
newnode = new node_type;
int info;
getdata(info); //first node
(*first).info = info;
(*first).next = nil;
getdata(info); //second node
(*newnode).info = info;
(*first).next = newnode;
(*newnode).next = nil;
p = newnode;
for (int i = 2; i < 8; i++) //nodes 3-8
{
newnode = new node_type;
getdata(info);
(*newnode).info = info;
(*p).next = newnode;
p = newnode;
(*newnode).next = nil;
}
q = first;
while (q != nil) // printing linked list
{
cout << (*q).info << "\n";
q = (*q).next;
}
//deletes last node then reverses list
p = first;
q = (*p).next;
r = (*q).next;
if (first == nil) //if list is empty
cout << "Empty list";
else if ((*first).next == nil) //if list has one node
first = nil;
else if (r == nil) //if list has two nodes
q = nil;
else //general case
{
(*first).next = nil; //last line where when i put a cout << ""; it prints in the output window
while ((*r).next != nil)
{
(*q).next = p;
(*r).next = q;
p = q;
q = r;
r = (*r).next;
}
(*q).next = p;
first = q;
}
q = first;
while (q != nil) // printing newly modified list.
{
cout << (*q).info << "\n";
q = (*q).next;
}
return 0;
}
void getdata(int & info)
{
cout << "Enter number: \n";
cin >> info;
}
【问题讨论】:
-
"省略了函数 [...] bc 我知道这不是问题的一部分" - 你怎么知道的?
-
因为它只用于创建原始列表的程序部分,并且该部分程序工作正常。为了安全起见,我会添加它
-
@Steve 读了一遍,谢谢。问题是我的程序编译得很干净,我没有收到任何错误或编译器警告或类似性质的东西。
-
first->info优于(*first).info等。
标签: c++ while-loop linked-list cout