这是我用C ++实现列表的程序。我输入元素直到0.程序显示第一个元素正确但第二个是错误的。我可能在第二个条件下犯错误
if (p -> next == first) {
secondElement = first -> data;
}
。你能说出它有什么问题吗?感谢
#include "stdafx.h"
#include "iostream"
using namespace std;
struct Node {
int data;
Node *next;
};
int firstElement;
int secondElement;
int main()
{
Node *first = 0;
Node *p;
cout << "Enter a list" << endl;
int i;
while (true) {
cin >> i;
if (i == 0) break;
p = new Node;
p -> data = i;
p -> next = first;
if (first == 0) {
first = p;
firstElement = first -> data;
}
if (p -> next == first) {
secondElement = first -> data;
}
first = p;
}
cout << "First element is: " << firstElement << endl;
cout << "Second element is: " << secondElement << endl;
cout << "List: ";
p = first;
while (p) {
cout << p -> data << " ";
p = p -> next;
}
cout << endl;
return 0;
}
答案 0 :(得分:1)
你可以这样做(我刚刚编辑了你的while循环):
while (true) {
cin >> i;
if (i == 0) break;
p = new Node;
p -> data = i;
p -> next = 0;
if (first != 0 && first->next == 0)
secondElement = p->data;
p -> next = first;
if (first == 0) {
first = p;
firstElement = first -> data;
}
first = p;
}
希望这是你想要实现的......
答案 1 :(得分:0)
每次循环都会将元素的指针设置为第一个。
p -> next = first;
然后在检查第二个元素时,你要检查指针是否设置为第一个,它始终是。
if (p -> next == first) // This is always true
您必须使用一些不同的检查来查看它是否是列表中的第二个条目,例如:
if (p->next && !p->next->next) // only true second time around
{
secondElement = p -> data; // also note the change here
}
答案 2 :(得分:0)
p -> next = first;
......
enter code here
if (p -> next == first) { //it's always true here
你应该有
if (p -> next == 0) {