【发布时间】:2022-01-01 19:24:29
【问题描述】:
C 中的单个链表节点中是否可以有多个数据?以及如何使用它输入和访问数据?
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
char name[30];
struct node *next;
};
struct node *head, *tail = NULL;
void addNode(int data, char string) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->name[30] = string;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
void sortList() {
struct node *current = head, *index = NULL;
int temp;
if(head == NULL) {
return;
}
else {
while(current != NULL) {
index = current->next;
while(index != NULL) {
if(current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
void display() {
struct node *current = head;
if(head == NULL) {
printf("List is empty \n");
return;
}
while(current != NULL) {
printf("%d - %s", current->data, current->name);
current = current->next;
}
printf("\n");
}
int main()
{
char string1[10] = "Aaron";
char string2[10] = "Baron";
char string3[10] = "Carla";
addNode(9, string1);
addNode(7, string2);
addNode(2, string3);
printf("Original list: \n");
display();
sortList();
printf("Sorted list: \n");
display();
return 0;
}
我不明白为什么我的代码不起作用。我试图使用单链表,它可以同时接受/输入和打印/输出数字和名称。
我希望它发生的是打印数字和名称。
输出应该是:
卡拉 - 2
男爵 - 7
亚伦 - 9
【问题讨论】:
-
newNode->name[30] = string;不正确。 -
“没用”从来都不是一个好的问题描述。请描述确切的输入、预期结果和实际结果。
-
正确的方法是什么?
-
strcpy(newNode->name, string); -
您将 char 参数传递给 addNode 函数,它应该是一个 char 数组。要设置名称,您需要使用
strncpy或其他等效函数将 char 数组参数复制到名称。
标签: c linked-list