开发者

Sorted linked list and the addSorted function problem.

开发者 https://www.devze.com 2023-04-07 04:26 出处:网络
So I\'ve been working on this for awhile and I can\'t seem to figure out what\'s wrong.This addSorted function adds in all the correct values in their respectable places of the sorted array but when i

So I've been working on this for awhile and I can't seem to figure out what's wrong. This addSorted function adds in all the correct values in their respectable places of the sorted array but when it goes into add a 0 to the front of the list, the program will not terminate and there is no result displayed. Anyone have any clue of why this may be?

void addSorted(Data * newData){
    if(head == NULL) {
        head = new LinkNode(newData);
        return;
    }
    LinkNode * current = head;
    LinkNode * previous = NULL;
    while(curre开发者_如何学Gont != NULL) {
        if(newData->compareTo(current->data) == -1) {
            LinkNode * newNode = new LinkNode(newData);
            newNode->next = current;
            if(previous == NULL) {
                current->next = newNode;
            }
            else {
                newNode->next = previous->next;
                previous->next = newNode;
            }
        return;
        }
    previous = current;
    current = current->next;
    }
previous->next = new LinkNode(newData);
}


Is the result of compareTo being -1 mean that it is less than the current node?

And if previous==NULL you set current->next to point to the newNode, which means they are pointing to each other, as newNode->next is also pointing to the current node.

I think the root of your problem may be this, actually.

       newNode->next = current;
       current->next = newNode;

Hopefully by putting it this way you can see what I am talking about.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号