链接列表排序插入第一次尝试

时间:2013-03-26 06:23:21

标签: visual-c++

我正在尝试为链表的排序插入编写c ++程序。我已经给出了下面的代码。问题是在进行第二次插入时,即插入(& head,45); 头部值在insert()函数内变为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;
}

1 个答案:

答案 0 :(得分:1)

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