请您解释一下,为什么函数“print”会在此代码中无限地打印一个相同的数字?
显然,链接列表构造正确,但在逐步调试时,它坚持“打印”功能。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct num {
int n;
num* next;};
void add (num*&head, int size) {
num*newnode = new num;
for (int i = 0; i<size; i++) {
newnode->n = rand()%100;
newnode->next = head;
head = newnode;}
}
void print (num*head) {
num*temp = head;
while (temp != 0) {
cout << temp->n << endl;
temp = temp ->next;}}
void del (num*&head) {
num*temp = 0;
while (head!=0){
temp = head;
head = head->next;
delete temp;}}
int main () {
srand ((unsigned int)time(0));
num*head = 0;
add (head, 10);
print (head);
del (head);
cin.get();
cin.ignore();
}
答案 0 :(得分:2)
问题在于添加功能。您没有创建新节点。而是修改同一节点并将其指向自身。
像这样改变
for (int i = 0; i<size; i++) {
newnode = new num; //new node
newnode->n = rand()%100;
newnode->next = head;
head = newnode;}
答案 1 :(得分:1)
您可以在add
功能
newnode->next = head;
head = newnode;
因此,只有一个节点及其next
指向head
,head
指向此节点。如果您在循环中移动num*newnode = new num;
,则可以解决此问题。