#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct node node;
struct node
{
int data;
struct node * next;
};
node* creat(int n)
{
node *head=new node;
head->next=NULL;
node *p=head;
while(n-->0)
{
node *t=new node;
scanf("%d",&t->data);
t->next=p->next;
p->next=t;
p=t;
}
return head;
}
void insertFront(node *head,int x)
{
node *t=new node;
t->data=x;
t->next=head->next;
head->next=t;
}
void print(node * head)
{
node * p=head->next;
while(p->next)
{
printf("%d ",p->data);
p=p->next;
}
printf("%d\n",p->data);
}
void destory(node *head)
{
node * p=head;
while(p)
{
node *t=p;
p=p->next;
delete t;
}
}
void Sort(node *head)
{
node *p,*q;
for(p=head->next; p; p=p->next)
{
for(q=head->next; q; q=q->next)
{
if(p->data<q->data)
{
int t=p->data;
p->data=q->data;
q->data=t;
}
}
}
}
node* LastKth(node *head,int k)
{
node *p=head->next;
int i=0;
while(p&&i<k)
{
p=p->next;
i++;
}
node *q=head->next;
while(p&&q)
{
p=p->next;
q=q->next;
}
return q;
}
node* Reverse(node *head) //逆置
{
if(head==NULL||head->next==NULL)
{
return NULL;
}
node *p,*q;
p=head->next;
head->next=NULL;
while(p)
{
q=p->next;
p->next=head->next;
head->next=p;
p=q;
}
return head;
}
int GetLength(node *head)
{
node * p=head->next;
int n=0;
while(p)
{
n++;
p=p->next;
}
return n;
}
bool hasCNode(node *h1,node *h2)
{
if(h1==NULL||h1->next==NULL||h2==NULL||h2->next==NULL)return false;
node *p=h1->next;
node *q=h2->next;
while(p->next)
{
p=p->next;
}
while(q->next)
{
q=q->next;
}
return p->data==q->data;
}
node *getCnode(node *h1,node *h2)
{
int n1=GetLength(h1),n2=GetLength(h2);
node *p=h1->next;
node *q=h2->next;
if(n1>n2)
{
while(p&&n1>n2)
{
p=p->next;
n1--;
}
}
else if(n1<n2)
{
while(q&&n2>n1)
{
q=q->next;
n2--;
}
}
while(p&&q)
{
if(p->data==q->data)return p;
p=p->next;
q=q->next;
}
return NULL;
}
int main()
{
int n1,n2;
while(scanf("%d%d",&n1,&n2)!=EOF)
{
node *h1=creat(n1);
node *h2=creat(n2);
node *t=getCnode(h1,h2);
if(t==NULL)
printf("My God\n");
else printf("%d\n",t->data);
destory(h1);
destory(h2);
}
return 0;
}
数据结构之单链表基本操作
最新推荐文章于 2024-09-09 21:22:51 发布