完成链串结构下的模式匹配(子串定位)应用。
输入一段字符串:They are student
它的子串:are
主串通过链表的形式存储,然后运用串模式匹配算法定位子串
#include <iostream>
#include<string.h>
using namespace std;
typedef struct Link {
char data;
struct Link * next;
}link,*Plink;
Plink initLink(Plink head, char * str);
void TraverseLink(Plink head);
void Match(Plink head,char *a,int &n);
int main()
{
Plink head = NULL;
int n;
char s[]="They are students";
char a[]="are";
head = initLink(head,s);
TraverseLink(head);
Match(head,a,n);
cout<<endl<<"the number of Match:"<<n<<endl;
return 0;
}
//初始化链表,其中head为头指针,str为存储的字符串
Plink initLink(Plink head, char * str) {
int length = strlen(str);
//根据字符串的长度,计算出链表中使用节点的个数
int i;
//创建并初始化首元节点
head = (Plink)malloc(sizeof(link));
head->next = NULL;
Plink temp = head;//头指针指向头结点
//初始化链表
for (i = 0; i<length; i++)
{
Plink newlink = (Plink)malloc(sizeof(link));
newlink->data=str[i];
newlink->next = NULL;
temp->next = newlink;//尾插法
temp = newlink;
}
return head;
}
//输出链表
void TraverseLink(Plink head) {
Plink temp = head->next;
while (temp) {
cout<<temp->data;
temp = temp->next;
}
}
//模式匹配
void Match(Plink head,char *a,int &n){
int length=0;
char b[30];
Plink p=head->next;
int i=0,j=0;
while(p){
b[length++]=p->data;
p=p->next;
}
while(i<length && j<strlen(a)){
if(b[i] == a[j]){
i++;
j++;
}else{
i=i-j+1;
j=0;
}
}
if(j==strlen(a)){
n=i-strlen(a)+1;
}else
n=0;
}