示例代码:
- struct node{ //使用递归结构处理链表
- int data;
- struct node *next;
- };
- struct node *creatlist(){ //创建链表的函数*createlist()
- struct node *h,*p,*q; //h头节点,p插入的节点,q尾节点
- int a;
- h=(struct node *)malloc(sizeof(struct node)); //h头节点,链表的起始地址
- p=q=h;
- scanf("%d",&a);
- while(a!=0){
- p=(struct node *)malloc(sizeof(struct node)); //p插入节点的起始位置
- p->data=a;
- q->next=p; //插入节点的地址存入当前节点的next
- q=p; //当前节点作为新节点的尾节点
- scanf("%d",&a);
- }
- p->next=NULL; //p的next为空,p就是尾节点
- return h;
- }
- void printlist(struct node *h){ //打印链表的函数printlist()
- struct node *p;
- p=h->next; //p时头节点的下一个节点
- while(p!=NULL){
- printf("-%d ",p->data);
- p=p->next; //取下一个节点
- }
- printf("\n");
- return;
- }
- main(){
- struct node *head;
- head=creatlist(); //创建链表并保存链表起始地址
- printlist(head); //输出链表
- }
- ------------------------------------------------------------------------------------------------
- //链表的增删改查
- struct Data{ //定义节点的数据类型
- int num;
- struct Data *next;
- };
- struct Data *insert(struct Data *head,struct Data *p0){ //插入节点 函数 *insert()
- struct Data *p1; //*p0 插入p1的前边,p2的后边
- struct Data *p2;
- p1=head;
- if(head==NULL){ //链表为空
- head=p0;
- p0->next=NULL;
- }else{
- while((p0->num>p1->num)&&(p1->next!=NULL)){ //查找待插入的位置
- p2=p1;
- p1=p1->next;
- }
- if(p0->num<=p1->num){ //按照num的大小决定p0的插入位置
- if(p1==head){ //p1是头节点,p0插入p1前边
- head=p0;
- p0->next=p1;
- }else{ //插入p2的后边,p1的前边
- p2->next=p0;
- p0->next=p1;
- }
- }else{ //插入尾节点的后边
- p1->next=p0;
- p0->next=NULL;
- }
- }
- return head;
- }
- void print(struct Data *head){ //输出链表的数据
- printf("链表中的数据:\n");
- if(!head) printf("链表为空:\n");
- while(head){
- printf("%5d -> ",head->num);
- head=head->next;
- }
- printf("NULL\n");
- }
- struct Data *release(struct Data *head){ //释放链表空间
- struct Data *p=head;
- while(p){
- head=p->next;
- free(p); //free()释放链表空间
- p=head;
- }
- printf("释放成功:\n");
- return head;
- }
- struct Data *EraseNode(struct Data *head,int n){ //删除节点
- struct Data *p1; //要删除的节点
- struct Data *p2; //p1的前一个结点
- if(head=NULL){ //链表为空
- printf("\n链表是空表:\n");
- return head;
- }
- p1=head;
- while((n!=p1->num)&&(p1->next!=NULL)){ //查找要删除的节点
- p2=p1;
- p1=p1->next;
- }
- if(n==p1->num){ //找到要删除的节点
- if(p1==head){ //要删除的是头节点
- head=p1->next;
- }else{
- p2->next=p1->next; //要删除的不是头节点
- }
- free(p1); //释放空间
- printf("已删除:%d\n");
- }else{ //没有找到
- printf("未找到\n");
- }
- return head;
- }