2012-03-25 56 views
0

我正在写一个程序,以根据字符串将元素插入到单个链表中(函数strcmp将它们放到正确的位置)。C++单链表(使用结构),插入错误

#include <iostream> 
#include <cstdlib> 
#include <cstring> 
using namespace std; 

struct list 
{ 
    int num; 
    char* word; 
    list* next; 
}; 
list* head; 
void insert(int number,char* txt){ 
    list* ptr,*tmp; 
     ptr=head; 
    list* newlist=new list; 
    newlist->num=number; 
    newlist->next=NULL; 
    //newlist->word= new char(strlen(txt)+1); 
    newlist->word=txt; 
    if(head==NULL){ 
     head=newlist; 
     newlist->next=NULL; 
    } 
    else while(ptr!=NULL){ 
      if(strcmp(txt,ptr->word)>=0){ 
       if(ptr->next!=NULL && strcmp(txt,ptr->next->word)<=0) 
      { 
       tmp=ptr->next; 
       ptr->next=newlist; 
       newlist->next=tmp; 
       break; 
      } 
       else if(ptr->next!=NULL && strcmp(txt,ptr->next->word)>0) 
        ptr=ptr->next; 
       else 
       { 
        //next is empty 
        ptr->next=newlist; 
        break; 
       } 
    } 
      else{ 
       //txt mniejszy niz w 1szym elemencie 
       newlist->next=head; 
       head=newlist; 
       break; 
      } 
      return; 
    } 
} 

void print(){ 
    list *druk; 
    druk=head; 
    while(druk!=NULL){ 
     cout<<"txt: "<<druk->word<<" | "<<"num: "<<druk->num<<endl; 
     druk=druk->next; 
    } 
    return; 
} 

int main(){ 

    head=NULL; 

    insert(242,"Szulasdj"); 
    insert(32,"aab"); 
    insert(32,"aab"); 
    insert(14,"aaa"); 
    insert(85,"bbb"); 
    insert(5,"aac"); 
    insert(3,"ccc"); 
    insert(4,"cdc"); 
    insert(2,"ccd"); 

    print(); 
    cout << endl << endl; 
    getchar(); 
    return 0; 
} 

我不明白为什么它不打印我插入的所有元素。如果你能告诉我我的错误在哪里,我会非常感激。

+1

这里有很多基本问题。首先,每次调用'insert'时,它会生成一个新的列表对象,然后导致内存泄漏。 – 2012-03-25 18:05:49

+0

能更准确地解释吗?另外我该如何解决它?除了遵循twain249的建议之外,它工作正常。 – 2012-03-25 18:21:06

回答

1

将返回移到while循环的外部。如果您进入了移动指针的情况,则必须再次通过while循环,并在返回之前退出该方法。