0

I am writing a program to insert elements into singly linked list based on their strings,(function strcmp is to put them into right place).

#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;
}

and I cannot figure out why it doesn't print all elements I inserted. If you could tell me where my mistake lies I would really appreciate it.

2
  • 1
    There are many fundamental problems here. For one thing, every time you call insert, it generates a new list object which then leads to a memory leak. Mar 25, 2012 at 18:05
  • could your explain more precisely? Also how can I fix it? Besides it is working fine, after I followed twain249's advise. Mar 25, 2012 at 18:21

1 Answer 1

1

Move the return outside of the while loop. If you get into the case where you move the pointer you have to go through the while loop again and that return exits the method before you do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.