38-8

给定两个链表,编写算法找出两个链表的公共结点

公共结点是指地址相同的结点,只有结点个数相同时,地址才会相同,画图理解

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

typedef struct node{
    int data;
    struct node *next;
}LNode,*LinkList;

void TailCreate(LinkList &L)
{
    L=(LinkList)malloc(sizeof(LNode));
    L->next=NULL;
    LNode *p,*r=L;
    int x;
    scanf("%d",&x);
    while(x!=999)
    {
        p=(LNode*)malloc(sizeof(LNode));
        p->data=x;
        p->next=NULL;
        r->next=p;
        r=p;
        scanf("%d",&x);
    }
}

void displayList(LinkList L)
{
    LNode *p=L->next;
    while(p!=NULL)
    {
        printf("%d  ",p->data);
        p=p->next;
    }
}

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

LNode* PublicNode(LinkList A,LinkList B)
{
    int Alen=Length(A);
    int Blen=Length(B);
    LNode *plong,*pshort;
    int dist;
    if(Alen>Blen)
    {
        plong=A->next;
        dist=Alen-Blen;
    }
    else
    {
        plong=B->next;
         dist=Blen-Alen;
    }
    while(dist--)
        plong=plong->next;
    while(plong!=NULL)
    {
        if(plong==pshort)
            return plong;
        else
        {
            plong=plong->next;
            pshort=pshort->next;
        }
    }
}

int main()
{
    LinkList L1,L2;
    TailCreate(L1);
    displayList(L1);
    printf("\n");
    TailCreate(L2);
    displayList(L2);
    printf("\n");
    
    return 0;
}

 

posted on 2023-10-06 10:38  四马路弗洛伊德  阅读(13)  评论(0)    收藏  举报

导航