题目:输入两个单链表,找出公共结点。
思路:若两个单链表有公共结点,其形状必定为“Y”型,也就是说公共结点后的所有结点都是相同的。
我们首先获得两个链表的长度,求得长度之差为n,再定义两个指针分别指向两个链表首部,长链表先走n步,然后两个指针同时走,直到两个指针所指向的值完全相同时停止。
代码:
/*
求链表公共结点
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct _NODE_
{
int data;
struct _NODE_ *next;
}Node,*pNode;
int get_length(pNode list)
{
if(list == NULL)
{
return 0;
}
int len = 0;
pNode pTemp = list;
while(pTemp != NULL)
{
len++;
pTemp = pTemp->next;
}
return len;
}
void create(pNode *list,int n)
{
if(n <= 0)
{
return;
}
*list = (pNode)malloc(sizeof(Node));
if(!list)
{
exit(-1);
}
int data;
scanf("%d",&data);
(*list)->data = data;
(*list)->next = NULL;
pNode pTemp = *list;
for(int i = 0; i < n-1; i++)
{
scanf("%d",&data);
pNode pNew = (pNode)malloc(sizeof(Node));
if(!pNew)
{
exit(-1);
}
pNew->data = data;
pNew->next = NULL;
pTemp->next = pNew;
pTemp = pNew;
}
}
//求单链表公共结点
pNode FindCommonNode(pNode list1,pNode list2)
{
if(list1 == NULL || list2 == NULL)
{
return NULL;
}
int len1 = get_length(list1);
int len2 = get_length(list2);
int dif = len1 - len2;
pNode pLong = list1;
pNode pShort = list2;
if(dif < 0)
{
pLong = list2;
pShort = list1;
dif = len2-len1;
}
while(dif > 0)
{
pLong = pLong->next;
dif--;
}
while(pLong != NULL && pShort != NULL && pLong != pShort)
{
pLong = pLong->next;
pShort = pShort->next;
}
return pLong;
}
void Destroy(pNode *list)
{
if(*list == NULL)
{
return;
}
pNode p = *list,q;
while(p != NULL)
{
q = p->next;
free(p);
p = q;
}
}