[英]Visual studio 2017 code not outputting after a certain line
我正在編寫一個程序,該程序需要8個用戶輸入的整數並從中生成一個鏈接列表。 我讓程序打印鏈接列表,然后刪除最后一個節點,然后反向打印列表。 在測試過程中,我一直在進行編程以確保每個部分都工作正常,並且可以完成打印原始鏈接列表的工作。
當我完成修改的代碼編寫並打印部分時,我遇到了一個問題-在打印出原始列表后,該程序將不會輸出任何內容。 例如,如果我輸入1,2,3,4,5,6,7,8,它將輸出:1 2 3 4 5 6 7 8就是這樣。 我已經嘗試過將cout <<“ testing”; 在不同的位置查看我的代碼停止輸出的位置,以及成功輸出的最新位置就在while循環之前。
我不確定為什么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;
}
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;
}
反轉列表時,您會陷入無限循環。 這就是為什么它不輸出任何東西的原因。
一旦將元素2鏈接到元素3,就在下一步中將元素3鏈接到元素2。
當在列表中進行反向迭代時,這將導致無限循環。
在一般情況下,將其反轉的正確方法如下:
else //general case
{
node_type* current = first;
node_type* next = first->next;
(*first).next = nil; //last line where when i put a cout << ""; it prints in the output window
while (next)
{
node_type* temp = next->next;
next->next = current;
current = next;
next = temp;
}
first = current;
}
在旁注中,應使用bla->foo
取消引用,而不是(*bla).foo
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.