寻找单链表存储字符串的相同后缀起始位置(4)

寻找单链表存储字符串的相同后缀起始位置(4)
时间复杂度为:O(min(m,n));

#include<stdio.h>
#include<stdlib.h>

//找出单链表存储的两个单词相同后缀的起始位置
//可以用栈来求,会比较简单,但是有空间上的消耗
//这里我直接来对比

//感觉链表现在写的越来越熟练了~开心~

typedef struct node
{
	char data;
	struct node* next;
}Node;

typedef struct list
{
	Node* head;
	Node* tail;
	int length;
}List;

void create_list(List *L)
{
	//头节点的指针是什么类型的呢
	Node * first = (Node*)malloc(sizeof(Node));
	if(!first)
		printf("create wrong!\n");
	first -> data = 0;
	first -> next = NULL;
	L->head = L->tail = first;
	L -> length = 0;
}

void insert_list(List *L,char value)
{
	Node * new = (Node*)malloc(sizeof(Node));
	if(!new)
		printf("insert wrong!\n");
	new -> data = value;

	L->tail -> next = new;
	new -> next = NULL;
	L->tail = new;
	L -> length ++;

}


Node* find_suffix(List l1, List l2)
{
	Node* p = l1.head->next;
	Node* q = l2.head->next;
	//if(l1.length > l2.length) //这里为了方便,就让l1的长度大于l2的长度
	//{

	//让两个字符串尾对齐
		int i = 0;
		while(i < l1.length - l2.length)
		{
			p = p->next;
			i++;
		}
	//}
	// else
	// {
	// 	int j = 0;
	// 	while(j < l2.length - l1.length)
	// 	{
	// 		q = q->next;
	// 		j++;
	// 	}

	// }

	Node *find;

	while(p) 
	{
		while(p && p->data != q->data) //找到两个字符串第一个相同字母的起始位置
		{
			p = p->next;
			q = q->next;
		}

		find = p;

		while(p && p->data == q->data) //这个循环巧妙,如果这里中间有不满足的,就重新回过头来找find
		{
			p = p->next;
			q = q->next;
		}

	}//while


	return find;

}


void print_list(List L)
{
	Node * p;
	//p = head;
	p = L.head -> next;
	while( p != NULL )
	{
		printf("%c ",p->data);
		p = p->next;
	}

	printf("\n");

	//printf("list length is %d\n",L.length);

}





int main(int argc, char const *argv[])
{
	List l1;
	List l2;
	create_list(&l1);
	create_list(&l2);

	insert_list(&l1,'l');
	insert_list(&l1,'o');
	insert_list(&l1,'a');
	insert_list(&l1,'d');
	insert_list(&l1,'i');
	insert_list(&l1,'n');//注意单引号和双引号的区别
	insert_list(&l1,'g');

	insert_list(&l2,'b');
	insert_list(&l2,'d');
	insert_list(&l2,'i');
	insert_list(&l2,'n');
	insert_list(&l2,'g');



	print_list(l1);
	print_list(l2);

	Node * result = find_suffix(l1,l2);

	printf("position is from %c\n", result->data);



	

	return 0;
}

运行截图
寻找单链表存储字符串的相同后缀起始位置(4)