したがって、これはリンクされたリストを作成して表示するための非常に単純なプログラムです。ここで私は表示ループに巻き込まれ、画面上に無限の '2->2->2->...' が表示されます。
デバッグ後、私のプログラムは常に のif
ステートメントに入ることがわかりますinsertNode()
が、リンクされたリストが初期化されたときに一度だけそこに行くべきです。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
struct node * head = NULL;
struct node * curr = NULL;
void insertNode(struct node * temp2) {
if (head == NULL) {
head = temp2;
head->next = NULL;
}
else {
temp2->next = head;
head = temp2;
}
}
void display() {
curr = head;
while (curr->next != NULL)
{
printf("%d->",curr->data);
curr = curr->next;
}
}
void main() {
struct node * temp = (struct node *) malloc (sizeof(struct node));
temp->data = 5;
insertNode(temp);
temp->data = 6;
insertNode(temp);
temp->data = 1;
insertNode(temp);
temp->data = 2;
insertNode(temp);
display();
}