数据结构之单链表——带有节点的单链表的创建、插入和删除(C/C++)

来源:互联网 发布:手机找不到wifi网络 编辑:程序博客网 时间:2024/05/30 19:33
// 带有头节点的单链表的创建、插入和删除
#include <stdio.h>#include <malloc.h>#include <stdlib.h>typedef int DataType;typedef struct LNode{DataType data;struct LNode *next;}LNode,*LinkList;// 这里的函数参数必须是链表的指针的地址,否则为局部变量无法将链表指针带回主程序// 创建带头节点的单链表void CreatListF( LinkList *head){*head=(LNode*)malloc(sizeof(LNode));(*head)->next=NULL;if(!*head)printf("debug\n");}// 从小到大插入void InsertList(LinkList head,DataType data){LinkList p=head,q;LNode *s;q=p;p=p->next;while(p && p->data<data){q=p;p=p->next;}s=(LNode*)malloc(sizeof(LNode));s->data=data;s->next=p;q->next=s;}// 删除,注意函数查不到的情况int DeleteList(LinkList head,DataType data){LinkList p=head,q;q=p;p=p->next;while(p && p->data!=data){q=p;p=p->next;}if(!p)return 0;// 为找不到到q->next=p->next;free(p);// 释放指针p=NULL;// 释放后指针指向NULLreturn 1;}void PrintList(LinkList head){LinkList p=head;while(p->next != NULL){p=p->next;printf("%d->",p->data);}printf("end\n");}// 主程序void main(){LinkList head=NULL;CreatListF(&head);// 这里很重要PrintList(head);InsertList(head,10);PrintList(head);InsertList(head,20);PrintList(head);InsertList(head,30);PrintList(head);InsertList(head,15);PrintList(head);DeleteList(head,15);PrintList(head);DeleteList(head,15);PrintList(head);}
运行结果:

0 0