C++ 如何比较链表的元素?
有人能解释一下为什么循环只迭代了3次吗C++ 如何比较链表的元素?,c++,linked-list,C++,Linked List,有人能解释一下为什么循环只迭代了3次吗 #include <iostream> using namespace std; struct Node{ Node *link; float x; }; Node *head = NULL; int main() { Node *first = new Node(); first -> x = 2.0; first -> link = NULL; head = first; Node *
#include <iostream> using namespace std;
struct Node{
Node *link;
float x; };
Node *head = NULL;
int main() { Node *first = new Node(); first -> x = 2.0; first
-> link = NULL; head = first;
Node *second = new Node(); first -> link = second; second -> x =
1.4; second -> link = NULL;
Node *third = new Node(); second -> link = third; third -> x =
3.4; third -> link = NULL;
////////////////////////////Delete /*Node *delfirst = head; head = head->link;*/ Node *a = head; Node *b = head;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
a = a -> link;
}
b = b -> link; } return 0; }
#包括使用名称空间std;
结构节点{
节点*链接;
浮点x;};
Node*head=NULL;
int main(){Node*first=new Node();first->x=2.0;first
->link=NULL;head=first;
节点*秒=新节点();第一个->链接=秒;第二个->x=
1.4;第二->链接=NULL;
节点*第三个=新节点();第二个->链接=第三个;第三个->x=
3.4;第三->链接=NULL;
////////////////////////////删除/*Node*delfirst=head;head=head->link;*/Node*a=head;Node*b=head;
对于(int i=0;i<3;i++){
对于(int j=0;j<3;j++){
a=a->link;
}
b=b->link;}返回0;}
代码如下所示
Node * a=head;
while(a->link)
{
Node * b=a->link;
while(b)
{
if(a->x == b->x)
dosomething();
b=b->link;
}
a=a->link
}
它只迭代了3次,因为这段代码在您的列表中只创建了3个节点,那么我如何比较“第一和第二个元素”,然后是“第一和第三个元素”,然后是“第二和第三个元素”等等?你能解释一下为什么这段代码的格式如此糟糕吗?这只是个例子。我正在学习链表。实际上我知道在这里使用“for”是不对的。什么循环?有两个,两个都有3次迭代…完全正确。非常感谢