c语言链表之动态创建尾插法
动态创建尾插法
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
struct Test *p = head;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
putchar('\n');
}
struct Test* inserBehind(struct Test *head, struct Test *new)
{
struct Test *p = head;
// 第一种情况,只有一个节点,那么该节点就是头节点
if(p == NULL){
p = new;
return p;
}
// 第三种情况,链表已经创建好,我需要另外再插入一个节点,
// 则需要不断遍历找到最后一个节点(最后一个节点的特点是next为null)
while(p->next != NULL){
p = p->next;
}
// 第二种情况,头节点已经确定,则需要把next指向下一个节点
p->next = new;
return head;
}
struct Test* createLink2(struct Test *head)
{
struct Test *new = NULL;
while(1){
new = (struct Test *)malloc(sizeof(struct Test));
puts("请输入数据!");
scanf("%d", &(new->data));
new->next = NULL;
if(new->data == 0){
printf("0 quit\n");
free(new);
return head;
}
head = insertFromTail(head, new);
}
}
int main()
{
struct Test *head = NULL;
head = createLink2(head);
printLink(head);
struct Test t2 = {2000, NULL};
head = inserBehind(head, &t2);
printLink(head);
}