c ++单链表(使用结构),插入有问题

时间:2012-03-25 17:55:40

标签: c++

我正在编写一个程序,根据字符串将元素插入单链表中,(函数strcmp是将它们放到正确的位置)。

#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 个答案:

答案 0 :(得分:1)

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