Brandon Tiqui
Brandon Tiqui

Reputation: 1439

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.

Upvotes: 0

Views: 1598

Answers (1)

Dan Lorenc
Dan Lorenc

Reputation: 5394

if(p = NULL)

That's your problem right there. It should be

if(p == NULL)

Upvotes: 3

Related Questions