1
새로운 노드를 추가하고 표시하는 기능을 가진 구조체를 만드는 프로그램에서 작업하고 있습니다. 나는 "add"라고 불리는 함수를 가지고 있는데, 새로운 노드를 만들고 struct-> next로 보내면 함수 "displayData"를 실행할 때마다 함수가 내 구조체가 NULL/empty라고합니다.포인터를 사용하여 구조체 만들기
다음은 코드입니다.
#include <stdio.h>
#include <stdlib.h>
typedef struct node *nodePtr;
struct node {
int item;
nodePtr next;
};
typedef nodePtr Statistician;
int input();
Statistician newStatistician(); //allocates memory to the structure. Dynamic allocation
void add(Statistician s, int x); //Adds data to the rear
void displayData(Statistician s); //prints entire dataset
int main() {
int operation, data;
Statistician s = NULL;
data = input(); //get new input
add(s,data); //run add function
displayData(s); //run display function
}
int input(){
int x;
printf("Enter data: ");
if (scanf("%d", &x) != 1)
{
printf("\n\nInvalid Input!\n\n");
exit(0);
}
return x;
}
Statistician newStatistician(){
Statistician newStat;
newStat = malloc(sizeof(struct node));
return newStat;
}
void add(Statistician s, int x){
Statistician newNode = newStatistician();
newNode->item = x;
newNode->next = NULL;
if(s == NULL){
s = newNode;
return;
}
while (s != NULL) {
s = s->next;
}
s->next = newNode;
}
void displayData(Statistician s){
Statistician temp = s;
if(s==NULL){
printf("\n\nList is EMPTY.");
printf("\n\nPress any key.\n");
getch();
return;
}
printf("\n\nThe List:\n");
while (temp != NULL) {
printf(" %d", temp->item);
temp = temp->next;
}
printf("\n\nPress any key.\n");
getch();
return;
}
내가 displayData를 사용할 때 출력은 다음과 같습니다.
List is EMPTY
감사처럼 호출 할 수 있습니다! –
@FrancisM 아니요. 천만에요.:) –