基于visual Studio2013解决面试题之0609寻找链表公共节点




题目



解决代码及点评

/*
	查找交叉链表中,第一个共同节点。

	这个链表是Y形状的链表,从第一个共同链表后,就是相同节点了
	解决思想:让长的链表先往前走几步,到步调一致时,一起往前遍历,找到相同节点

*/


#include <iostream>
using namespace std;

typedef struct node
{
	int data;
	struct node* next;

}Node;

Node* create_Node_NoRing(int a[],int len)
{
	Node* head,*p,*q;
	p=new Node();
	p->data=a[0];
	head=p;
	p=new Node();
	p->data=a[1];
	head->next=p;

	for (int i=2;i<len;i++)
	{
		q=new Node();
		q->data=a[i];
		p->next=q;
		p=q;
	}
	p=NULL;
	return head;
}

bool IsMeeting(Node* head1,Node* head2,int lena,int lenb)
{
	Node* fast,*slow;
	int duff=0;
	if (lena>lenb)
	{
		duff=lena-lenb;
		fast=head1;
		slow=head2;
	}
	else
	{
		duff=lenb-lena;
		fast=head2;
		slow=head1;
	}
	while(duff)
	{
		fast=fast->next;
		duff--;
	}
	while(fast!=slow && fast!=NULL && slow!=NULL)
	{
		slow=slow->next;
		fast=fast->next;
	}
	if (fast==slow && fast!=NULL && slow!=NULL )
	{
		return true;
	}
	return false;

}


Node* FirstMeet(Node* head1,Node* head2,int lena,int lenb)
{
	Node* fast,*slow;

	// 计算两个链表的长度差值
	int duff=0;
	if (lena>lenb)
	{
		duff=lena-lenb;
		fast=head1;
		slow=head2;
	}
	else
	{
		duff=lenb-lena;
		fast=head2;
		slow=head1;
	}
	// 长的那个链表,先往前走diff步
	while(duff)
	{
		fast=fast->next;
		duff--;
	}

	//  然后一起走,找到相同的节点
	while(fast->data!=slow->data && fast!=NULL && slow!=NULL)
	{
		slow=slow->next;
		fast=fast->next;
	}

	// 打印
	if (fast->data==slow->data && fast!=NULL && slow!=NULL )
	{
		return fast;
	}
	return NULL;

}


int main()
{
	int a[]={1,2,3,4,5,6,7};
	int b[]={12,11,10,9,5,6,7};
   //int b[]={12,11,10};
	int lena=sizeof(a)/sizeof(int);
	int lenb = sizeof(b)/sizeof(int);
	// 创建链表
	Node* head1 = create_Node_NoRing(a,lena);
	Node* head2 = create_Node_NoRing(b,lenb);

	// 查找
	cout<<FirstMeet(head1,head2,lena,lenb)->data<<endl;
	//cout<<IsMeeting(head1,head2,lena,lenb)<<endl;


	system("pause");
	return 0;
}



代码下载及其运行

代码下载地址:http://download.csdn.net/detail/yincheng01/6704519

解压密码:c.itcast.cn


下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:

1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”


2)在下拉框中选择相应项目,项目名和博客编号一致

3)点击“本地Windows调试器”运行


程序运行结果









posted on 2013-12-18 00:44  三少爷的剑123  阅读(134)  评论(0编辑  收藏  举报

导航