using namespace std;
#include <iostream>
typedef struct Node{
int data;
Node *next;
};
Node *createList(int num)
{
Node *Head = new Node;
// Head = nullptr;
Head ->next = nullptr;
Node *prev = Head;
for (int i = 0; i < num; ++i)
{
cout << "Enter "<< i+1 << endl;
Node *temp = new Node;
cin >> temp->data;
prev ->next = temp;
prev = temp;
temp ->next = nullptr;
}
return Head;
}
void display(Node * head)
{
cout << "Now:";
while(head != nullptr)
{
cout <<head->data << " ";
head = head ->next;
}
}
int main(void)
{
int num;
cout << "Enter How?" ;
cin >> num;
cout << endl;
Node *head;
head = createList(num);
display(head);
return 0;
}
这是段测试链表的代码,为什么每次输出都有一个垃圾数?是因为new没有释放吗?