我正在尝试用c ++实现链接列表,但似乎无法理解为什么我不能停止从终端获取输入。
Node* take_input_better() {
int data;
cin >> data;
Node *head = NULL;
Node *tail = NULL;
while(data != -1) {
cout << "debug" << endl;
Node *newNode = new Node(data);
if(head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail -> next = newNode;
tail = tail -> next;
// OR
// tail = newNode;
}
cout << "Debug" << endl;
cin >> data;
}
return head;
}
此函数仅使用该元素创建一个链表,直到输入-1。 如果我输入第一个元素为-1。它似乎工作正常。但是,当我已经输入一些数据后,如果它不是-1,则该程序似乎需要无数的输入,并且该流甚至不在while语句内,因为不会显示“ debug”和“ Debug”字样。
编辑1:这是完整程序
Node.cpp
class Node {
public:
int data;
Node *next;
Node(int data){
this->data = data;
next = NULL;
}
};
linked_list.cpp
#include <iostream>
using namespace std;
#include "Node.cpp"
Node* take_input_better() {
int data;
cin >> data;
Node *head = NULL;
Node *tail = NULL;
while(data != -1) {
cout << "debug" << endl;
Node *newNode = new Node(data);
if(head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail -> next = newNode;
tail = tail -> next;
// OR
// tail = newNode;
}
cout << "Debug" << endl;
cin >> data;
}
return head;
}
int length(Node *head){
Node *temp = head;
int count = 0;
while(temp != NULL){
count++;
}
return count;
}
int main(){
Node *head = take_input_better();
cout << "Length of the Linked List: " << length(head) << endl;
}
答案 0 :(得分:1)
错误在length
函数中。您没有向前移动temp
指针。这样做:
int length(Node *head){
Node *temp = head;
int count = 0;
while(temp != NULL){
count++;
temp = temp->next;
}
return count;
}
熟悉调试器。是你的朋友。
答案 1 :(得分:-1)
您还需要确保输入流处于可读状态(例如cin.good()
)。如果它进入失败状态,cin >> data
将继续运行,但无需等待新的用户输入或将任何有意义的值放入data
。