1

我正在尝试编写一个用于排序插入链表的 C++ 程序。我已经给出了下面的代码。问题是在进行第二次插入时,即insert(&head, 45); 在 insert() 函数中,head 值变为 0。我无法插入第二个元素并出现错误。任何人都可以请帮忙。

#include "stdafx.h"
#include <conio.h>
#include <iostream>

using namespace std;

struct node
{
    int data;
    node *next;
};

void insert (node** head, int key)
{
    if(*head == NULL)
    {
        cout <<"List is empty, Inserting at first posistion"<<endl;
        *head = new node;
        (*head)->data = key;
        (*head)->data = NULL;
    }
    else
    {
        struct node* temp;
        temp = new node;
        temp = *head;

        if(key < temp->data)
        {
        cout<<"Key is smaller than first element. Inserting at first and moving"<<endl;
            struct node* ctemp = new node;
            ctemp->data = key;
            ctemp->next = (*head);
            //delete(ctemp);
            return;
        }

        while(temp->next != NULL)
        {
            if(key > temp->data)
            {
                temp = temp->next;
            }else
            {
                cout<<"Inserting the data at middle"<<temp->data<<" here"<<endl;
                struct node* temp1 = new node;
                temp1->data = key;
                temp1->next = temp->next;
                temp->next = temp1;
                delete(temp1);
                return;
            }
        }

        if(key > temp->data)
        {
            cout<<"Inserting at last"<<endl;    
            struct node* last = new node;
            last->data = key;
            last->next = NULL;
            temp->next = last;
            delete(last);
            return;
        }
    }
}

void print(struct node *head)
{
    struct node* temp = head;
    cout<<"Element in the list"<<endl;
    while(temp != NULL)
    {
        cout<<temp->data<<"->";
        temp = temp->next;
    }
    delete(temp);
}

int main()
{
    struct node* head = NULL;
    insert(&head, 21);
    insert(&head, 45);
    insert(&head, 5);

    print(head);
    getch();
    delete(head);
    return 0;
}
4

1 回答 1

1

如果列表为空,请更改(*head)->data = NULL;为。(*head)->next = NULL;

于 2013-03-26T06:27:47.460 回答