赞
踩
- //单链表的创建、初始化、插入、删除 、输出、求表长、清空、查找操作
- #include<stdio.h>
- #include<stdlib.h>
- #include<malloc.h>
- #define N 5
- #define ERROR 0
- #define OK 1
- typedef struct node{ //定义节点
- int data;
- struct node *next;
- }linklist;
- linklist *Initlist() //初始化单链表
- {
- linklist *head;
- head=(linklist*)malloc(sizeof(linklist));
- head->next=NULL;
- return head;
- }
- linklist *CreateList(int n) //用尾插法创建单链表
- {
- int i;
- linklist *head,*p,*r;
- head=(linklist*)malloc(sizeof(linklist));
- head->next=NULL;
- r=head;
- for(i=1;i<=n;i++)
- {
- p=(linklist*)malloc(sizeof(linklist));
- p->next=NULL;
- scanf("%d",&p->data);
- r->next=p;
- r=r->next;
- }
- return head;
- }
- void printlist(linklist *head) //输出链表
- {
- linklist *p;
- int i=1;
- p=head->next;
- while(p!=NULL)
- {
- printf("%d:",i);
- printf("%d\n",p->data);
- p=p->next;
- i++;
- }
- printf("\n");
- }
- void listlength(linklist *head) //求表长
- {
- int count=0;
- linklist *p;
- p=head->next;
- while(p!=NULL)
- {
- count++;
- p=p->next;
- }
- printf("链表的长度为%d\n",count);
- }
- int insertlist(linklist *head,int i,int x) //在第i个位置上插入新的元素
- {
- int j;
- linklist *p,*s;
- p=head;
- j=0;
- while(p!=NULL&&j<i-1)
- {
- p=p->next;
- j++;
- }
- if(p==NULL||i<1) return ERROR;
- s=(linklist*)malloc(sizeof(linklist));
- s->data=x;
- s->next=p->next;
- p->next=s;
- return OK;
- }
- int deletelist(linklist *head,int i) //删除i位置上面的元素
- {
- int j;
- linklist *p,*q;
- p=head;j=0;
- while(p!=NULL&&j<i-1)
- {
- p=p->next;
- j++;
- }
- if(p==NULL||i<1) return ERROR;
- q=p->next;
- p->next=q->next;
- free(q);
- return OK;
- }
- int locatelink(linklist *head,int x) //求元素x在链表的哪个位置
- {
- linklist *p;
- int j;
- p=head->next;
- j=1;
- while(p!=NULL&&p->data!=x)
- {
- p=p->next;
- j++;
- }
- if(p==NULL) return ERROR;
- else return j;
- }
- int clearlist(linklist *head) //清空链表
- {
- linklist *p,*q;
- p=head->next;
- head->next=NULL;
- while(p!=NULL)
- {
- q=p;
- p=p->next;
- free(q);
- }
- return 1;
- }
- int main()
- {
- linklist *head;
- head=CreateList(5); //输入的元素为 1 3 5 7 9
- printlist(head);
- listlength(head);
- int i;
- i=locatelink(head,5);
- printf("5的位置为%d\n",i);
- insertlist(head,6,10);
- printlist(head);
- printf("\n");
- deletelist(head,5);
- printlist(head);
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。