问题在代码部分,这是缩写版的,,,纠结
#include <iostream>
using namespace std;
struct Node
{
int sx;
int sy;
Node *next;
};
class Test1
{
Node *head;
int x;
int y;
public:
Test1(int _x , int _y)
:x(_x),y(_y){}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
void Initiate()
{
head = new Node;
head->sx = x;
head->sy = y;
head->next = NULL;
}
void Add(int tx ,int ty)//在链表头添加元素
{
Node *temp = new Node;
temp->sx = tx;
temp->sy = ty;
temp->next = head;
head = temp;
}
void Del()//在链表末尾删除元素
{
Node *temp = head;
while(temp->next != NULL)
temp = temp->next;
delete temp;
temp = NULL;
}
void Print()//为什么打印这里会无线执行?
{
Node *temp = head;
while(temp->next != NULL)
cout << temp->sx << “–” << temp->sy << endl;
}
};
int main()
{
int i = 1 , j = 1;
Test1 ts(i , j);
ts.Initiate();
for(int k = 0 ; k < 3 ; ++k)
ts.Add(++i , ++j);
cout << “ppp” << endl;
for(int k = 0 ; k < 4 ; ++k)
ts.Print();
return 0;
}
#include <iostream>
using namespace std;
struct Node
{
int sx;
int sy;
Node *next;
};
class Test1
{
Node *head;
int x;
int y;
public:
Test1(int _x , int _y)
:x(_x),y(_y){}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
void Initiate()
{
head = new Node;
head->sx = x;
head->sy = y;
head->next = NULL;
}
void Add(int tx ,int ty)//在链表头添加元素
{
Node *temp = new Node;
temp->sx = tx;
temp->sy = ty;
temp->next = head;
head = temp;
}
void Del()//在链表末尾删除元素
{
Node *temp = head;
while(temp->next != NULL)
temp = temp->next;
delete temp;
temp = NULL;
}
void Print()//为什么打印这里会无线执行?
{
Node *temp = head;
while(temp->next != NULL)
cout << temp->sx << “–” << temp->sy << endl;
}
};
int main()
{
int i = 1 , j = 1;
Test1 ts(i , j);
ts.Initiate();
for(int k = 0 ; k < 3 ; ++k)
ts.Add(++i , ++j);
cout << “ppp” << endl;
for(int k = 0 ; k < 4 ; ++k)
ts.Print();
return 0;
}
解决方案
40
每次while(temp->next != NULL)循环都没有改变temp,当然一直在循环了
你应该每次循环让temp = temp->next吧
你应该每次循环让temp = temp->next吧
40
#include <iostream>
using namespace std;
struct Node
{
int sx;
int sy;
Node *next;
};
class Test1
{
Node *head;
int x;
int y;
public:
Test1(int _x, int _y)
:x(_x), y(_y){}
int get_x()
{
return x;
}
int get_y()
{
return y;
}
void Initiate()
{
head = new Node;
head->sx = x;
head->sy = y;
head->next = NULL;
}
void Add(int tx, int ty)//在链表头添加元素
{
Node *temp = new Node;
temp->sx = tx;
temp->sy = ty;
temp->next = head;
head = temp;
}
void Del()//在链表末尾删除元素
{
Node *temp = head;
while (temp->next != NULL)
temp = temp->next;
delete temp;
temp = NULL;
}
void Print()//为什么打印这里会无线执行?
{
Node *temp = head;
while (temp->next != NULL)
{
cout << temp->sx << "--" << temp->sy << endl;
temp = temp->next;
}
}
};
int main()
{
int i = 1, j = 1;
Test1 ts(i, j);
ts.Initiate();
for (int k = 0; k < 3; ++k)
ts.Add(++i, ++j);
cout << "ppp" << endl;
for (int k = 0; k < 4; ++k)
ts.Print();
return 0;
}