第一种:头插法
#include <stdio.h>
#include <stdlib.h>
struct Link
{
int data;
struct Link *next;
};
void print(struct Link *head)
{
struct Link *p = head;
while(p){
printf("%d ",p->data);
p = p->next;
}
puts("\n");
}
struct Link* head_insert(struct Link* head,struct Link* new)
{
if(head == NULL){
head = new;//如果头结点为空,则新结点为头结点
//return head;
}else{
new->next = head;//将新结点指向头结点
head = new;//新结点为头结点
}
return head;
}
struct Link* create_link(struct Link* head)
{
struct Link* new = NULL;
while(1){
new = (struct Link*)malloc(sizeof(struct Link));//每输入一个新结点之前,就开辟一个空间
printf("please input new node data\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("0 quit\n");//输入0则程序退出
free(new);//释放掉所开辟的空间,防止内存泄漏
return head;
}
head = head_insert(head,new);
}
}
int main()
{
struct Link *head = NULL;
head = create_link(head);
print(head);
struct Link T1 = {88,NULL};
head = head_insert(head,&T1);
print(head);
return 0;
}
第二种:尾插法
#include <stdio.h>
#include <stdlib.h>
struct List
{
int data;
struct List* next;
};
void print(struct List * head)
{
struct List *p = head;
while(p){
printf("%d ",p->data);
p = p->next;
}
puts("\n");
}
struct List* tail_insert(struct List* head,struct List* new)
{
struct List* p = head;
if(p == NULL){
head = new;
return head;
}
while(p->next != NULL){
p = p->next;
}
p->next = new;
return head;
}
struct List* create_list(struct List* head)
{
struct List* new = NULL;
while(1){
new =(struct List*)malloc(sizeof(struct List));
printf("please input node data\n");
scanf("%d",(&new->data));
if(new->data == 0){
printf("0 quit\n");
free(new);
return head;
}
head = tail_insert(head,new);
}
}
int main()
{
struct List *head = NULL;
struct List T1 = {88,NULL};
head = create_list(head);
print(head);
head = tail_insert(head,&T1);
print(head);
return 0;
}