0

I have a function and it is suppose to organize a dictionary of stemmed words. I have a function call inserted then suppose to place it in the right alphabetical order. Adding to the front and middle of the list works, but adding to the back doesn't. I've looked at several sources and I can't tell what's wrong.

void dictionary::insert(string s) {
    stem* t = new stem;

    t->stem = s;
    t->count =0;
    t->next = NULL;

    if (isEmpty()) head = t;
    else {
        stem* temp = head;
        stem* prev =  NULL;

        while (temp != NULL) {
            if (prev == NULL && t->stem < temp ->stem) {
                head = t;
                head->next = temp;
            }
            prev = temp;
            temp = temp->next;

            if(t->stem > prev->stem && t->stem < temp->stem ){
                prev->next =t;
                t->next=temp;
            }
        }

        if(temp == NULL && t->stem > prev->stem){  
            prev->next=t;
        }
    }
}
pb2q
  • 58,613
  • 19
  • 146
  • 147

2 Answers2

1
if (temp->next=NULL) {
    prev->next = t; 
}

Note the usage of a single equal. The effect of this is to set the temp->next to NULL and then evaluate if (NULL) witch will be always false. You should use ==.


This will probably do the job: (sorry, I don't have a compiler right now to test it)

#include <string>

struct node;
struct node
{
    node* next;
    std::string value;
};

node* head = NULL;

void insert(const std::string& word)
{
    node* n = new node;
    n->value = word;
    node* temp = head;
    node** tempp = &head;
    while (true)
    {
        if (temp == NULL or temp->value > word)
        {
            n->next = temp;
            *tempp = n;
            return;
        }
        temp = temp->next;
        tempp = &temp->next;
    }
}
Guilherme Bernal
  • 8,183
  • 25
  • 43
  • good eye , but still not the problem, iv even tryied prev->next =t; outside the loop cause prev should be last element in the list and just fails at the line in prev->next=t; in both case – user1547386 Oct 11 '12 at 00:22
  • like for example while(temp !-> null){ // add to front , //add to mid,} prev->next =t; where prev is the last element but fails and the end – user1547386 Oct 11 '12 at 00:23
  • thanks for trying but dont work, theres an infinte loop which is what im having problems with now :/ – user1547386 Oct 11 '12 at 00:56
1

The statement if(temp->next=NULL) does not result in a boolean but rather an assignment. This is why the insert to the end of the list doesn't appear to work.

bobestm
  • 1,334
  • 1
  • 9
  • 8