數據結構複習(四)線性表的某些題目

數據結構 線性表

2.3.7 第22題

找共同後綴的起始位置

我就返回的是起始元素處於較長的鏈表的序號了

代碼如下:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
#include<stack>
#include<cstring>
using namespace std;

typedef struct LNode
{
    char data;
    struct LNode *next;
}LNode,*LinkList;

void ini(LinkList &head)
{
    head=(LNode*)malloc(sizeof(LNode));
    head->next=NULL;
}

void Insert(LinkList &head,char a[],int n)
{
    LNode *r,*s;
    r=head;
    for(int i=0; i<n; i++)
    {
        s=(LNode*)malloc(sizeof(LNode));
        s->data=a[i];
        r->next=s;
        r=s;
    }
    r->next=NULL;
}




int Length(LinkList& L)
{
    int Count=0;
    LNode* p=L->next;
    while(p){
        Count++;
        p=p->next;
    }
    return Count;
}

int Share(LinkList& L1,LinkList& L2)
{
    LNode* p1=L1->next,*p2=L2->next;
    int len1=Length(L1);
    int len2=Length(L2);
    int len,pos=0;
    if(len1>len2)
    {
        len=len1-len2;
        pos=len;
        while(len--)
            p1=p1->next;
    }
    else
    {
        len=len2-len1;
        pos=len;
        while(len--)
            p2=p2->next;
    }
    while(p1&&p2)
    {
        if(p1->data==p2->data){
            return pos;
        }
        else
        {
            p1=p1->next;
            p2=p2->next;
            pos++;
        }
    }
    return pos;
}


int main()
{
    LinkList L1,L2;
    ini(L1);
    ini(L2);
    char a[7]={'l','o','a','d','i','n','g'};
    char b[5]={'b','e','i','n','g'};
    Insert(L1,a,7);
    Insert(L2,a,7);

    cout<<Share(L1,L2)<<endl;


    return 0;
}

結果:
結果
因爲是統考題,就順便記錄一下了。。。其實挺簡單的,主要是手寫代碼太心累了唉

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