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