求兩個字符串的公共後綴

求兩個字符串的公共後綴:

例子: zhong #

            zong #

           公共的後綴爲:ong

算法的基本思路:

  • 求出str1,str2的長度,len1,len2
  • 設置兩個指針p/q分別指向str1 ,str2,如果len1>=len2,指針p指向str1所指的鏈表第len1-len2+1個位置上的節點;如果len2>len1,指針q指向鏈表q的第len2-len1+1個位置上的節點。這樣就可以將兩個鏈表對齊了
  • 從對齊的位置開始,同時向後移動指針p,q。當出現p->data=q->data,即找到公共位置的起始位置。

 

/********************************************************************
 * @author:zjl
 * @brief: find  the common back
 * @date:29-5-2020
 * ******************************************************************/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct Node{
    char data;
    struct Node *next;
}Node,*Linklist;

//head  insert  method
/**
 * @brief createlist
 * @return
 * @attention input your char  and  end by '#'
 */
Linklist createlist(){
    char x;
    Linklist head=(Linklist)malloc(sizeof(Node));
    Linklist list=head;
    list->next=NULL;
    scanf("%c",&x);
    while(x!='#'){
      Linklist pNew=(Linklist)malloc(sizeof(Node));
      pNew->data=x;
      list->next=pNew;
      pNew->next=NULL;
      list=pNew;
      scanf("%c",&x);
    }
    return  head;

}
/**
 * @brief traverseList
 * @param head
 * @return
 */
Linklist traverseList(Linklist head)
{
   Node *p=head;
   printf("common element:");
   while(p!=NULL){
       printf("%c",p->data);
       p=p->next;
   }
   printf("\n");
}
/**
 * @brief linkedLen
 * @param head
 * @return
 */
int linkedLen(Linklist head)
{
   int len=0;
   while(head->next!=NULL)
   {
       len++;
       head=head->next;
   }
   return  len;
}
/**
 * @brief locateTail
 * @param str1
 * @param str2
 * @return
 */
Linklist locateTail(Linklist str1,Linklist str2)
{
    int  len1=linkedLen(str1);
    int  len2=linkedLen(str2);
    Node *p,*q;
    for(p=str1;len1>=len2;len1--){
        p=p->next;
    }
    for(q=str2;len1<len2;len2--){
        q=q->next;
    }
    while(p->next!=NULL&&p->next->data!=q->next->data){
        p=p->next;
        q=q->next;
    }
    return p->next;
}
int main(int argc,char * argv[]){

    Linklist str1,str2;
    str1=createlist();
    str2=createlist();
 //   traverseList(str1->next);
 //   traverseList(str2->next);
    cout<<endl;
    traverseList(locateTail(str1,str2));
    return 0;
}
/********************************************@copyright2020*********end of  file*******************************/

 

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