title: 链表基本操作date: 2020-10-18 22:44:41
tags: C++
categories: 算法
code
#include <iostream>#include <string>using namespace std;#define MAXLEN 40#define ERROR 0#define OK 1#define NOT -1typedef struct{ char ch[MAXLEN]; int len; } SString;//函数:创建链表void initSString(SString *p,char ch_[MAXLEN]){ strcpy(p->ch,ch_); p->len = strlen(p->ch);}//函数:在指定坐标前插入字符串(在LA和LB段间接上LC段)int Insert(SString *s, int pos, const SString *t){ int i; if (pos < 0 || pos > s->len) //插入位置不合法 return ERROR; if (s->len + t->len <= MAXLEN) //A+B+C <= MAXLEN { for (i = s->len + t->len - 1; i >= pos + t->len; i--) s->ch[i] = s->ch[i - t->len]; for (i = 0; i < t->len; i++) s->ch[i + pos] = t->ch[i]; s->len = s->len + t->len; } else if (pos + t->len <= MAXLEN) //A+B <= MAXLEN C要截取 { for (i = MAXLEN - 1; i >= pos + t->len; i--) s->ch[i] = s->ch[i - t->len]; for (i = 0; i < t->len; i++) s->ch[i + pos] = t->ch[i]; s->len = MAXLEN; } else //A <= MAXLEN B和C都要截取 { for (i = 0; i < MAXLEN - pos; i++) s->ch[i+pos] = t->ch[i]; } return OK;}//函数:从pos下标位置开始,删除l个元素StrDelete(SString *s, int pos, int l){ int i; if (pos < 0 || pos > (s->len - l)) return ERROR; for (i = pos + l; i < s->len; i++) s->ch[i - l] = s->ch[i]; s->len = s->len - l; return OK;}//函数:求从主串pos下标开始,返回第一个子串首元素下标,没有返回0int index_BF(const SString *s,const SString *sub,int pos){ if(pos < 0 || pos > (s->len-1)) return ERROR; int i = pos;int j = 0; int lens = strlen(s->ch); int lensub = strlen(sub->ch); while(i < lens && j < lensub) { if(s->ch[i] == sub->ch[j]){i++;j++;} else {i = i-j+1;j = 0;} } if(j >= sub->len) return i - j; else return NOT; //不是子串}main(){ int t = 0; char str[100]; SString s = {"abcdef",6}; SString sub = {"labcde",6}; SString a; cout<<"Input: "<<endl; cin>>str; initSString(&a,str); cout<<a.ch<<endl; cout<<a.len<<endl; return 0;}