Summary Report
Thanks for all the helpful feedback. cin.clear()
was very helfpul; so was the remark about setting next
to NULL. But the final problem (as diagnosed in the comments) was that I was using Ctrl+D
to escape, and cin >> k
wasn't handling this correctly. When I added k > 0
into the while condition (see updated code) and escaped with a negative number, it all started working.
I hate to post large amounts of code, but I don't think I can trim this any further. The point is that my program works the first go-around, but not the second. (Skip to main
to see what I mean.)
#include <iostream>
using namespace std;
struct ListNode {
int data;
ListNode* next;
};
void print_list(ListNode* node) {
cout << node->data << endl;
while ((node = node->next) != NULL) {
cout << node->data << endl;
}
}
ListNode* read_list() {
ListNode *head, *tail;
int k;
head = NULL;
while ((cin >> k) && k > 0) {
if (head == NULL) {
head = tail = new ListNode;
} else {
tail->next = new ListNode;
tail = tail->next;
}
tail->data = k;
tail->next = NULL;
}
return head;
}
int main() {
ListNode *list1, *list2;
list1 = read_list();
print_list(list1); // Works
list2 = read_list();
print_list(list2); // Does not work!
return 0;
}
And then here is the output:
Press ENTER or type command to continue
1
3
5
7
List1
1
3
5
7
List2
Command terminated
Do you see how it terminates before printing List2
? (The first four lines are from stdin. See main
.) What is going wrong here? I don't understand why the same logic would work the first time, but not the second.
Perhaps it's because I am not freeing the memory for the first linked list?