在C语言中用尾插法建立带头结点的单链表
时间: 2024-05-12 20:20:30 浏览: 8
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node, *LinkList;
LinkList createList(){
LinkList head = (LinkList)malloc(sizeof(Node));
head->next = NULL;
return head;
}
void tailInsert(LinkList L, int data){
Node *p = L;
while(p->next != NULL){
p = p->next;
}
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
p->next = newNode;
}
void printList(LinkList L){
Node *p = L->next;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main(){
LinkList L = createList();
tailInsert(L, 1);
tailInsert(L, 2);
tailInsert(L, 3);
tailInsert(L, 4);
printList(L);
return 0;
}
```