这是段测试链表的代码,为什么每次输出都有一个垃圾数?是因为new没有释放吗?

using namespace std;
#include 
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 <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没有释放吗?

img

因为你这是有固定头结点的链表,所以输出时,头结点不要输出。

void display(Node * head)
{
    cout << "Now:";
    head = head->next;
    while(head != nullptr)
    {
        cout <<head->data << " ";
        head = head ->next;
    }