2013-03-26 136 views
1

我想編寫一個c + +程序的鏈接列表的排序插入。我已經給出了下面的代碼。問題是當我做第二次插入時,即插入(& head,45);插入()函數裏頭值變爲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

如果列表爲空,則將(*head)->data = NULL;更改爲(*head)->next = NULL;

+0

謝謝指出。我在編程中犯了很多像這樣的愚蠢錯誤。如何克服這一點?任何想法? – nathan1138 2013-03-26 07:15:21

+0

練習很多。 – 2013-03-26 07:48:25