/********************************************************
* 串的簡單模式比對 *
********************************************************/
#include <stdio.h>
#include <stdlib.h>
/* 定義單鏈表結構體 */
struct node
{
char ch;
struct node *next;
};
/* 初始化單鏈表 */
void init(struct node **h)
{
*h = (struct node*)malloc(sizeof(struct node));
(*h)->next = NULL;
return;
}
/* 將x結點插入到鏈表後 */
void append(struct node *p, int x)
{
struct node *s;
s = (struct node*)malloc(sizeof(struct node));
s->ch = x;
s->next = NULL;
/* 移動到表尾 */
while (p->next != NULL)
{
p = p->next;
}
p->next = s;
return;
}
void display(struct node *p)
{
printf("You typed string is: ");
while (p->next != NULL)
{
printf("%c", p->next->ch);
p = p->next;
}
printf(" ");
return;
}
int main(int argc, char *argv[])
{
struct node *t, *s; /* s為主串, t為模式串 */
struct node *sNext, *p, *q;
int i, x = 0;
init(&s);
printf("Please type main string: ");
while (x != ' ')
{
x = getchar();
if (x != ' ')
{
append(s, x); /* 添加到表尾 */
}
}
display(s);
init(&t);
printf("Please type substring: ");
x = 0;
while (x != ' ')
{
x = getchar();
if (x != ' ')
{
append(t, x); /* 添加到表尾 */
}
}
display(t);
/* 初始化 */
sNext = s->next;
p = sNext;
q = t->next;
i = 1;
/* 從開始字元進行比較 */
while ((p->next != NULL) && (q->next != NULL))
{
/* 進行匹配檢驗 */
if (p->ch == q->ch)
{
p = p->next;
q = q->next;
}
else
{
sNext = sNext->next;
p = sNext; /* 指向主串中的下一個 */
q = t->next; /* 指標後退重新開始匹配 */
i++; /* 記錄位置 */
}
}
/* 輸出結果 */
if ((q->next) == NULL && (t->next->ch == s->next->ch))
{
printf("match position: %d", i);
}
else
{
printf("Not match!");
}
printf(" ");
return 0;
}