字符串链式存储结构的基本运算

来源:互联网 发布:淘宝店铺智能版 编辑:程序博客网 时间:2024/05/16 18:32
/** *@Name:字符串链式存储结构的基本运算  *@Description:空串的创建,串初始化、遍历、元素的插入、删除和修改和移动。 *@Author:Freedoman *@Date: 2014-8-12 */ #include <stdio.h>#include <stdlib.h>#include <string.h>/*字符结点*/struct Node{char c;struct Node * next;};typedef struct Node * PNode;/*函数声明*/PNode createNullLinkedString(void);int isNullLinkedString(PNode pstr);int initLinkedString(PNode pstr);int insertBeforeElement(PNode pstr);int dtempteElement(PNode pstr);void printString(PNode pstr);/*----------创建一个空的字符串---------------*/PNode createNullLinkedString(){PNode pstr=(PNode)malloc(sizeof(struct Node));if(pstr != NULL){pstr->next=NULL;pstr->c='-';printf("创建成功!\n");}else{pstr=NULL;printf("创建失败!\n");}return pstr;}/*-----------判断串是否为空----------------*/ int isNullLinkedString(PNode pstr){if(pstr->next == NULL){printf("空串!\n");return 1;}else{printf("非空串!\n");return 0;}}/*----------初始化一个空字符串-------------*/int initLinkedString(PNode pstr){PNode cur = pstr;if(isNullLinkedString(pstr)){while(1){char c;printf("输入字符(@结束)>>>");scanf("%c",&c);getchar();if(c =='@'){break;}// 申请要插入的结点 PNode temp = (PNode)malloc(sizeof(Node));temp->next = NULL;temp->c = c;if(pstr->next == NULL){pstr->next = temp;cur = pstr;}else{cur->next->next = temp;cur = cur->next;}} printf("初始化完毕!\n");printString(pstr);return 1;}else{printf("初始化失败!\n");return 0;}}/*-----------在指定字符之前插入字符---------------*/int insertBeforeElement(PNode pstr,char c,char s){PNode cur = pstr;while(cur->next != NULL){// 找到指定字符 if(cur->next->c == c) { PNode temp = (PNode)malloc(sizeof(PNode));temp->c = s;temp->next = cur->next;cur->next = temp; printf("插入成功!\n");printString(pstr);return 1;}cur = cur->next;}printf("未找到指定字符,插入失败\n");return 0;}/*---------删除指定元素----------*/int deleteElement(PNode pstr,char c){PNode cur = pstr;while(cur->next != NULL){// 找到指定字符 if(cur->next->c == c){cur->next = cur->next->next;printf("删除成功!\n");printString(pstr);return 1; }cur = cur->next;}printf("删除失败!\n");return 0;}/*----------打印当前字符串----------*/void printString(PNode pstr){PNode cur = pstr;printf("[");while(cur->next != NULL){printf(" %c ",cur->next->c);cur = cur->next;}printf("]");}/*-------主控-------*/int main(void){PNode pstr= NULL;printf("\n--------字符串的基本操作---------\n");char c,s,ch;int input;while(1){printf("\n 1_创建空串\n 2_判断当前是否为空\n 3_初始化空串\n");printf(" 4_在指定字符之前插入字符\n 5_删除指定字符\n 6_打印串\n");printf("\n请选择>>>"); scanf("%d",&input);scanf("%c",&ch); switch(input){case 1 : pstr = createNullLinkedString();break;case 2 : isNullLinkedString(pstr);break;case 3 : initLinkedString(pstr);break;case 4 : printf("请指定字符>>>");scanf("%c",&c);getchar();printf("请输入要插入的字符>>>");scanf("%c",&s);insertBeforeElement(pstr,c,s);break;case 5 :printf("请指定字符>>>");scanf("%c",&s); deleteElement(pstr,s);break;case 6 : printString(pstr);break;default: printf("输入错误,请重新输入"); break;}}return 0;}

0 0
原创粉丝点击