请你解释一下,为什么函数“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();
}
最佳答案
问题出在添加功能上。您不是在创建新节点。而是修改同一个节点并将其指向自身。
这样改
for (int i = 0; i<size; i++) {
newnode = new num; //new node
newnode->n = rand()%100;
newnode->next = head;
head = newnode;}
关于c++ - 链表 C++ 的错误打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646114/