求相同後綴首字符(單鏈表)

1、題目:


 Problem Description

現用單鏈表保存字符串,假定有兩個字符串存在相同的後綴,請輸出該相同後綴的首字符。

 Input

有多組數據,每組包含兩個字符串。(串長小於1600)

 Output

輸出該相同後綴的首字符。

 Sample Input

loading
being
cat
eat

 Sample Output

i
a

2、參考代碼:

#include <iostream>
#include <string.h>
using namespace std;

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

class LinkList{
private:
	Node* head;
public:
	LinkList(char* a,int n);
	~LinkList();
	void oper(int x,char* a);
	void show(char* a);
};

LinkList::LinkList(char* a,int n){
	Node* r,* s;
	head=new Node;
	r=head;
	for(int i=0;i<n;i++)
	{
		s=new Node;
		s->data=a[i];
		s->next=r->next;
		r->next=s;
		r=s;
	}
	r->next=NULL;
}

LinkList::~LinkList(){
	Node* p,* q;
	p=head;
	while(p){
		q=p;
		p=p->next;
		delete q;
	}
}

void LinkList::oper(int x,char* a){
	Node* p;
	p=head->next;
	int i=0;
	while(p && i<x){
		head=head->next;
		p=head->next;
		i++;
	}
	int j=0;
	while(p && j<strlen(a)){
		if(p->data==a[j]){
			cout<<p->data<<endl;
			return ;
		}
		p=p->next;
		j++;
	}
}

void LinkList::show(char* a){
	Node* p;
	p=head->next;
	int i=0,len=strlen(a);
	while(p && i<len){
		if(p->data==a[i]){
			cout<<p->data<<endl;
			return ;
		}
		i++;
		p=p->next;
	}
}

int main()
{
	int s1,s2;
	char str1[2222],str2[2222];
	while(cin>>str1>>str2){
		s1=strlen(str1);
		s2=strlen(str2);
		if(s1>s2){
			LinkList w1(str1,s1);
			int x1=s1-s2;
			w1.oper(x1,str2);
		}else if(s1<s2){
			LinkList w2(str2,s2);
			int x2=s2-s1;
			w2.oper(x2,str1);
		}else{
			LinkList w3(str1,s1);
			w3.show(str2);
		}
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章