原理图
//单链表 头插法
struct Node {
char name;
int score;
int length;
struct Node *next;
};
typedef struct Node ListNode;
/*在链表的头部插入新的节点,建立链表 n 结点个数*/
ListNode *createList(int n) {
ListNode *head; //指向头结点的指针
ListNode *newNode = NULL; //链表指针
head = (ListNode *)malloc(sizeof(ListNode)); //为 头 节点分配内存空间
head->next = NULL; //将头结点的指针域清空
for(int i = 1; i <= n ; i++) { //通过for循环不断加入新的结点
newNode = (ListNode *)malloc(sizeof(ListNode)); //为要 插入的 节点分配空间
printf("please input name of the %d student:",i);
scanf("%s",&newNode->name);
printf("please input score of the %d student:",i);
scanf("%d",&newNode->score);
if (i == 1) {
head->next = newNode;
}
else {
newNode->next = head->next;
head->next = newNode;
}
head->length = i;
}
return head; //返回这个链表的首地址
}
/*输出链表*/
void printList(ListNode *h) {
ListNode *p;
p = h->next; //让p指针 指向链表头结点
for (int i = 0; i < h->length; i++) {
printf("%c,%d",p->name,p->score);
p = p->next;
printf("\n");
}
printf("链表长度:%d\n",h->length);
}
/*在 main()函数中调用*/
int main() {
ListNode *list = createList(3);
printList(list);
return 0;
}