链表是数据结构中的首先接触到的,常规的链表数据域为int型,如果链表中数据域是一个结构体该如何操作呢?
首先看一个例子:
定义一个学生结构体,然后用单向链表保存学生信息,由scanf输入学生信息后形成链表,再打印出所有学生信息
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
char name[20];
int age;
int score;
}student;
typedef struct node_t
{
student data;
struct node_t *next;
}Node;
Node *init()
{
Node *head=malloc(sizeof(struct node_t));
head->next=NULL;
return head;
}
void insert(Node *head,int age,int score,char *name)
{
Node *p=malloc(sizeof(struct node_t));
Node *q=head;
while(q->next!=NULL)
q=q->next;
q->next=p;
strcpy(p->data.name,name);
p->data.age=age;
p->data.score=score;
p->next=NULL;
}
int main()
{
Node *head=init();
int l,i,age,score;
char name[20];
printf("input lenght of list: ");
scanf("%d",&l);
for(i=0;i<l;i++)
{
printf("input age of node: ");
scanf("%d",&age);
printf("input score of node: ");
scanf("%d",&score);
printf("input name of node: ");
scanf("%s",name);
insert(head,age,score,name);
}
Node *p=head;
while(p->next!=NULL)
{
p=p->next;
printf("%-3d",p->data.age);
printf("%-3d",p->data.score);
printf("%s\n",p->data.name);
}
return 0;
}
作者:conspicuous
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。