资源描述:
《单链表的建立及其基本操作的实现(完整程序).doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include"stdio.h"/*单链表方式的实现*/#include"malloc.h"typedefcharElemType;typedefstructLNode/*定义链表结点类型*/{ElemTypedata;structLNode*next;}LNode,*LinkList;/*注意与前面定义方式的异同*//*建立链表,输入元素,头插法建立带头结点的单链表(逆序),输入0结束*/LinkListCreateList_L(LinkListhead){ElemTypetemp;LinkListp;printf("请输入结点值(输入0结束)");fflush(stdin);s
2、canf("%c",&temp);while(temp!='0'){if(('A'<=temp&&temp<='Z')
3、
4、('a'<=temp&&temp<='z')){p=(LinkList)malloc(sizeof(LNode));/*生成新的结点*/p->data=temp;p->next=head->next;head->next=p;/*在链表头部插入结点,即头插法*/}printf("请输入结点值(输入0结束):");fflush(stdin);scanf("%c",&temp);}returnhead;}/*顺序输出链表的内容*/voidListPint_L(Link
5、Listhead){LinkListp;inti=0;p=head->next;while(p!=NULL){i++;printf("单链表第%d个元素是:",i);printf("%c",p->data);p=p->next;}}/*在带头链表结点的单链表中第i(从1开始)个位置之后插入元素*/intLinkInsert_L(LinkListhead,inti,ElemTypee){LinkListp=head;LinkLists;intj;p=p->next;for(j=1;jnext;elsebreak;}if(!p
6、
7、i<1){pr
8、intf("error!!请输入正确的i的值!!");return0;}s=(LinkList)malloc(sizeof(LNode));s->data=e;s->next=p->next;/*在当前结点p之后插入结点s*/p->next=s;return1;}/*在带头结点的单链表中删除第i(从1开始)个位置的元素*/intListDel_L(LinkListhead,inti){LinkListp,tmp;intj;p=head->next;tmp=head;for(j=1;j
9、->next;tmp=tmp->next;}elsebreak;}if(!p
10、
11、i<1){printf("error!!请输入正确的i值!!");return0;}tmp->next=p->next;free(p);return1;}voidmain(){inti;charcmd,e;LinkListhead;head=(LinkList)malloc(sizeof(LNode));head->next=NULL;CreateList_L(head);ListPint_L(head);do{printf("i,I……插入");printf("d,D……删除");printf("q,Q
12、……退出");do{fflush(stdin);scanf("%c",&cmd);}while((cmd!='d')&&(cmd!='D')&&(cmd!='i')&&(cmd!='I')&&(cmd!='q')&&(cmd!='Q'));switch(cmd){case'i':case'I':printf("请输入您要插入的数据:");fflush(stdin);scanf("%c",&e);printf("请输入您要插入的位置:");scanf("%d",&i);LinkInsert_L(head,i,e);ListPint_L(head);break;case'd':case'
13、D':printf("请输入您要删除的位置:");fflush(stdin);scanf("%d",&i);ListDel_L(head,i);ListPint_L(head);break;}}while((cmd!='q')&&(cmd!='Q'));}