电话面试:求两个链表的第一个公共结点

来源:互联网 发布:黑手党3低配优化 编辑:程序博客网 时间:2024/05/16 07:08

求两个链表的第一个公共结点

题目另外一种说法也可以为两个链表第一个交点。首先确定相交在链表上的含义,链表相交意味着某个节点到链表尾都是相同。其实这个问题可以联想到路程相遇问题,如何使得两个链表同时到第一个公共结点,其实很简单,如果得到两个链表长度,然后长的链表直接从它比短链表长的数目的结点开始,则设定两个指向链表的指针就能实现功能。

#include <iostream>using namespace std;typedef struct Linklist{int val;Linklist *next;}*listPoint;void insertNode(listPoint &head,int val){Linklist *pre=NULL,*current=NULL;if (head==NULL){head=new Linklist;head->val=val;head->next=NULL;}else{current=head;while (current!=NULL&¤t->val<val){pre=current;current=current->next;}Linklist *newNode=new Linklist;if (newNode==NULL){cout<<"memory error\n";}newNode->val=val;pre->next=newNode;newNode->next=current;}}int GetLinklistLen(Linklist *head){int len=0;while (head!=NULL){len++;head=head->next;}return len;}Linklist *FindFirstNode(Linklist *head1,Linklist *head2){int len1=GetLinklistLen(head1);int len2=GetLinklistLen(head2);int diff=len1-len2;Linklist *listLong=head1;Linklist *listshort=head2;if (len1<len2){diff=len2-len1;listLong=head2;listshort=head1;}for (int i=0;i<diff;i++){listLong=listLong->next;}while (listshort!=NULL&&listLong!=NULL&&(listshort!=listLong)){listshort=listshort->next;listLong=listLong->next;}if (listshort==NULL||listLong==NULL){cout<<"链表不存在相交点\n";return (Linklist*)NULL;}return listshort;}int main(){int a[]={4,5,6};int b[]={1,2,3,5,6};Linklist *head1=NULL,*head2=NULL;Linklist *head3=NULL;for (int i=0;i<3;i++){insertNode(head2,b[i]);}Linklist *curr=head2;while (curr->next!=NULL){curr=curr->next;}for (int i=3;i<5;i++){insertNode(head3,b[i]);}head1=new Linklist;head1->val=4;head1->next=head3;curr->next=head3;cout<<"第一个相交元素为"<<FindFirstNode(head1,head2)->val<<endl;}


 

0 0
原创粉丝点击