开发者

Why is my printList function not working?

开发者 https://www.devze.com 2022-12-13 17:22 出处:网络
#include <iostream> using namespace std; struct Node { char item; Node *next; }; void inputChar ( Node * );
#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->开发者_Python百科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)
0

精彩评论

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