The program will read values that are typed in by the user iteratively in a while loop. Every time the value is read, a new node will be created with this integer value. Now I'll make a LinkedList using these created nodes. And then print out every value stored in the LinkedList. I expect the order of reading in and the order of printing out are reversed. The following is my main function where readline is just a function that prints a message and reads an input, make_new_node is a function that takes in a value and makes a new node with this value, printlink is the function that prints out all the values saved in every node in the linked list, and freelink contains the free function. For now, I only get a printed-out result of the last integer typed in. With just one node variable n, how can I possibly print out all the value members of every node in the linked list?
int main()
{
char buf[100];
int num;
Node* n = NULL;
while(1) {
readline("The num to put in?: ", buf, sizeof(buf));
sscanf(buf, "%d", &num);
if(num == -1) {
n -> next = NULL;
printlink(n);
freelink(n);
break;
} else {
n = make_new_node(num);
n -> next = n;
}
}
return 0;
}
答案 0 :(得分:0)
Store a reference to the first node. Since you never add any nodes before this one you could just have a method that takes the first node and iterates through your list via next.
Alternatively you could make a doubly linked list where you have a next AND a previous variable. Your method could then find the first node by going back via previous.
答案 1 :(得分:0)
This is how you would generally approach this, but I guess it breaks your rule about using only a single node pointer? Is that a limitation specified in how you are allowed to solve the problem, or just a limitation you ran into based on your implementation?
int main()
{
char buf[100];
int num;
Node *head = NULL, *n;
while(1){
readline("The num to put in?: ", buf, sizeof(buf));
sscanf(buf, "%d", &num);
if (num == -1){
printlink(n);
freelink(n);
break;
} else{
n = make_new_node(num);
n -> next = head;
head = n;
}
}
return 0;
}
答案 2 :(得分:0)
The most common way is to change the signature of make_new_node
to
Node * make_new_node(int new_value, Node *current_head);
Code then become:
} else {
n = make_new_node(num, n);
}
A classical stack implementation is for example
Node * make_new_node(int new_value, Node *current_head) {
Node *n = malloc(*Node);
n->value = new_value;
n-> next = current_head;
return n;
}
But in that case, this
if(num == -1) {
n -> next = NULL; // NO!
would immediately trunk the (stack) linked list to only one element, all other would be leaked...