struct node{
char name[50];
double grade;
struct node* next;
};
void append(struct node* root){
int n;
printf("Enter the number of students: ");
scanf("%d",&n);
while(n !=0){
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the name of the student: ");
scanf("%s",&temp->name);
printf("\nEnter the grade for the student named %s: ",temp->name);
scanf("%f",&temp->grade);
temp->next=NULL;
if(root==NULL){
root=temp;
}else{
struct node* iterate=root;
while(iterate->next != NULL){
iterate=iterate->next;
}
iterate->next=temp;
}
n--;
}
}
int listLength(struct node* root){
struct node* temp = root;
int counter=0;
while(temp !=NULL){
counter++;
temp=temp->next;
}
return counter;
}
int main()
{
struct node* root = NULL;
append(&root);
//printList(&root);
printf("Node length: %d",listLength(&root));
return 0;
}
이것이 제가 연결 목록으로 시작하는 한 제가 가지고있는 것입니다. 함수를 사용하여 여러 연결 목록에 추가 할 수 있도록 만들려고했습니다. 그래서 메인에 다른 루트 포인터를 만들고 노드를 추가하기위한 매개 변수로 append 함수를 호출합니다.
이것은 작동하는 것처럼 보이지만 목록 시작 부분에 빈 노드를 추가합니다. 이 노드에는 데이터가 없습니다. 예를 들어 4 명의 학생을 목록에 추가하면 nodeLength 함수는 5를 반환합니다.
struct node{
char name[50];
double grade;
struct node* next;
};
struct node * append(struct node* root){
int n;
printf("Enter the number of students: ");
scanf("%d",&n);
while(n !=0){
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the name of the student: ");
scanf("%s",&temp->name);
printf("\nEnter the grade for the student named %s: ",temp->name);
scanf("%f",&temp->grade);
temp->next=NULL;
if(root==NULL){
root=temp;
}else{
struct node* iterate=root;
while(iterate->next != NULL){
iterate=iterate->next;
}
iterate->next=temp;
root=iterate;
}
n--;
}
return root; }
int nodeLength(struct node* root){
struct node* temp = root;
int counter=0;
while(temp !=NULL){
counter++;
temp=temp->next;
}
return counter;
}
int main()
{
struct node* root = NULL;
root= append(root);
//printList(&root);
printf("Node length: %d",nodeLength(root));
return 0;
}
이 코드를 확인하여 조금 이해하십시오. 더 설명하겠습니다.
그리고 반환 유형을 캐스트하지 마십시오 malloc
.
매개 변수를 올바르게 변경 한 경우 여기에서 수행하는 작업이 제대로 작동 struct node**
하지만 예와 같이 더 쉽게 수행 할 수 있습니다 (위에 표시된 예). 이중 포인터를 사용하는 것보다 자연스럽고 직관적입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다