数据结构复习(四)线性表的某些题目

数据结构 线性表

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;
}

结果:
结果
因为是统考题,就顺便记录一下了。。。其实挺简单的,主要是手写代码太心累了唉

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