// CreatLinklist.cpp : Defines the entry point for the console application. //创建一个链表并输出最后销毁链表 #include <stdlib.h> #include <stdio.h> #define N 5//链表节点个数 struct node { int data; node *next; }; void creat_linklist(node *L)//创建 { int num,i; node *q=NULL; node *head=L; scanf("%d",&num); head->data=num;//链表头赋值 node *p=(node *)malloc(sizeof(node)); head->next=p; /*更简便些 for(i=1;i<=N-2;i++) //中间元素赋值 { scanf("%d",&num); p->data=num; p->next=(node *)malloc(sizeof(node)); p=p->next; }*/ for(i=1;i<=N-2;i++) //中间元素赋值 { scanf("%d",&num); p->data=num; q=p; p=(node *)malloc(sizeof(node)); q->next=p; } scanf("%d",&num);//最后一个元素赋值 p->data=num; p->next=NULL; } void print_link(node *L)//打印 { node *p=L; while(p!=NULL) { printf("%d/n",p->data); p=p->next; } } int insert_link(node **head,int value)//插入到一个有序的单链表 ,最终版本,要修改指针head的值,所以传参用** { node *newn; node *current=*head; while(current!=NULL && current->data<value) { *head=current->next; current=current->next; } newn=(node *)malloc(sizeof(node)); newn->data=value; *head=newn; newn->next=current; return 0; } void destroy_link(node *L { node *q=NULL; node *p=L; while(p) { q=p->next; free(p); p=q; } } int main(int argc, char* argv[]) { node *headL=(node *)malloc(sizeof(node)); headL->next=NULL; creat_linklist(headL); insert_link(&headL,0); print_link(headL); destroy_link(headL); system("pause"); return 0; }