简体   繁体   中英

Why is my printList function not working?

#include <iostream>
using namespace std;

struct Node
{
    char item;
    Node *next; 
};

void inputChar ( Node * );
void printList (Node *);
char c;


int main()
{

    Node *head;
    head = NULL;
    c = getchar();
    if ( c != '.' )
    {
        head = new Node;
        head->item = c;
        inputChar(head);
    }
    cout << head->item << endl;
    cout << head->next->item << endl;
    printList(head);
    return 0;
}

void inputChar(Node *p)
{
    c = getchar();
    while ( c != '.' )
    {
        p->next = new Node;             
        p->next->item = c;
        p = p->next;
        c = getchar();
    } 
    p->next = new Node; // dot signals end of list              
    p->next->item = c;
}

void printList(Node *p)
{
    if(p = NULL)
        cout << "empty" <<endl;
    else
    {
        while (p->item != '.')
        {
            cout << p->item << endl;
            p = p->next;
        }
    }
}

This program takes input from the user one character at a time and places it into a linked list. printList then attempts to print the linked list. The cout statements immediately before the call to printList in main work fine but for some reason the printList function hangs up in the while loop.

if(p = NULL)

That's your problem right there. It should be

if(p == NULL)

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