简体   繁体   中英

Linked List push()

The stack is initialized with a int MaxSize =3. Then I push one int onto the list. " Pushed:" is returned to the console. Program crashes here. I think my logic is flawed but unsure. Maybe an infinite loop or unmet condition? Thanks for your help.

I'm trying to traverse the list to the last node in the second part of the full() method. I implemented this stack as array based so must implement this method full() as this method is inside of main class.

while(!stacker.full()) {
    cout << "Enter number = ";
    cin >> intIn;
    stacker.push(intIn);
    cout << "Pushed: " << intIn <<  endl;
}//while

Call to LinkListStack.cpp to class LinkList full().

int LinkList::full() {
    if(head == NULL) {
        top = 0;
    } else {
        LinkNode * tmp1;
        LinkNode * tmp2;
        tmp1 = head;
        while(top != MaxSize) {
            if(tmp1->next != NULL){
                tmp2 = tmp1->next;
                tmp1 = tmp2;
                ++top;
            }//if
        }//while
    }//else
return (top + 1 == MaxSize);
}

The push method here:

void LinkList::push(int numIn) {
    LinkNode * nodeIn = new LinkNode(numIn);
    if(head == NULL) {
        head = nodeIn;
    }else {
        nodeIn = head;
        head = nodeIn;
    }
}

Look at your while loop in full():

while(top != MaxSize) {
        if(tmp1->next != NULL){
            tmp2 = tmp1->next;
            tmp1 = tmp2;
            ++top;
        }//if
    }//while

So if you have one element in the list you enter the while loop(assuming top == 0 ?), and since it's the first node in the list tmp1->next is NULL , which keeps top from being incremented, so you're stuck in the loop.

You also shouldn't need tmp2 , you can just use tmp1 = tmp1 -> next; .

And to correct the problem look at the if statment, Why are you checking to make sure the next node is not null?

Also, look in push():

void LinkList::push(int numIn) {
    LinkNode * nodeIn = new LinkNode(numIn);
    if(head == NULL) {
        head = nodeIn;
    }else {
        nodeIn = head;
        head = nodeIn;
    }
}

You should be setting nodeIn->next to head , before pointing head at nodeIn . The way it is written the new node is never added to the list.

int LinkList::full() {
        int top = 0;
        LinkNode * tmp1;
        tmp1 = head;
        while(top <= MaxSize && tmp1 != NULL) {
                tmp1 = tmp1->next;
                ++top;
        }//while
    return (top <= MaxSize);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM