赞
踩
链式存储结构大同小异,不再多叙述
//链表结构体
typedef struct Snode {
char ch;
struct Snode *next;
} LinkStrNode;
//初始化结构体
void initSnode(LinkStrNode *&node) {
node = (LinkStrNode*)malloc(sizeof(LinkStrNode));
node->next = NULL;
}
#define MaxSize 6
//创建链表
void createLinkStr(LinkStrNode *&node) {
char chs[MaxSize] = {'a','b','c','d','e','f'};
int index = 0;
LinkStrNode *r , *p;
r = node;
for(index;index < MaxSize ; index++){
p = (LinkStrNode*)malloc(sizeof(LinkStrNode));
p->ch = chs[index];
r->next = p; r = p;
}
r->next = NULL;
}
//销毁串算法
void destoryStr(LinkStrNode *&node){
LinkStrNode *pre = node , *p = node->next;
while(p!=NULL){
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
//输出链表
void DispStr(LinkStrNode *&node){
LinkStrNode *r;
r = node->next;
while(r != NULL){
printf("%3c",r->ch);
r = r->next;
}
}
//串的复制操作
void copyStr(LinkStrNode *preNode,LinkStrNode *&newNode){
initSnode(newNode);
LinkStrNode *pre = preNode->next , *r , *p;
r = newNode;
while(pre != NULL){
p = (LinkStrNode*)malloc(sizeof(LinkStrNode));
p->ch = pre->ch;
r->next = p; r = p;
pre = pre->next;
}
r->next = NULL;
}
//判断两个字符串是否相等 void strEqual(LinkStrNode *preNode,LinkStrNode *newNode){ LinkStrNode *p = preNode->next , *q = newNode->next; if(p == NULL || q == NULL){ printf("空链不比较"); exit(0); } bool flag = false; while(p != NULL && q != NULL && p->ch == q->ch){ p = p->next; q = q->next; } if(p == NULL && q == NULL){ flag = true; } if(flag){ printf("相等"); }else{ printf("不相等"); } }
//求串的长度
int strLength(LinkStrNode *node){
LinkStrNode *p = node->next;
int len = 0;
while(p!=NULL){
len++;
p = p->next;
}
return len;
}
//连接串 void concat(LinkStrNode *p , LinkStrNode *q , LinkStrNode *&n){ int len = strLength(p) + strLength(q); //获取长度 LinkStrNode *s1 = p->next , *s2 = q->next , *r; initSnode(n); r = n; int index = 0; printf("\n%3d",len); while(index < len){ //拼串 if(s1!=NULL){ r->next = s1; s1 = s1->next; }else{ r->next = s2; s2 = s2->next; } r = r->next; index++; } r->next = NULL; }
LinkStrNode *s , *newNode , *n; initSnode(s); createLinkStr(s); DispStr(s); copyStr(s,newNode); printf("\n"); DispStr(newNode); printf("比较两个字符串:\n"); strEqual(s,newNode); printf("\n"); int len = strLength(newNode); printf("求字符串长度为:%3d",len); concat(s,newNode,n); printf("\n"); DispStr(n); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。