c-单个链表节点中的多个数据



是否可以在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

Baron-7

Aaron-9

请阅读我标记为// CHANGE HERE的评论。

// CHANGE HERE: accept a character array as argument
void addNode(int data, char string[]) {  
struct node *newNode = (struct node*)malloc(sizeof(struct node));  
newNode->data = data; 
// CHANGE HERE: copy char array argument to name
strncpy(newNode->name, string, 30);
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;  
char temp1[30];

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; 

// CHANGE HERE: swap the name along with data
strncpy(temp1, current->name, 30);
strncpy(current->name, index->name, 30);
strncpy(index->name, temp1, 30);

}  
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 - %sn", current->data, current->name);  
current = current->next;  
}  
printf("n");  
}

最新更新