#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);
}
printList(head);
return 0;
}
void inputChar(Node *p)
{
getchar();
while ( c != '.' )
{
p->next = new Node;
p->next->item = c;
inputChar(p->next);
}
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;
printList(p->next);
}
}
}
I am trying to make a linked list of characters that are input by the user. A period indicates the end of the input. My program keeps looping on the inputChar function. Any ideas?
Perhaps you should add:
Still, it’s kind of dangerous what you are doing. In some platforms,
getchar()will return immediately after consuming the ENTER key of the previousgetchar()call. So you should consider that in your loop. Perhaps adding an extragetchar()to the inputChar function?Also, what Paul wrote is true. You should change your
whileloop with a simpleif.