从此篇博文开始,讲解一道古老的链表相交问题,共五篇
题目
给出俩个单向链表的头指针,比如 h1,h2,判断这俩个链表是否相交
解题步骤
struct ListNode{
int data;
ListNode * nextNode;
ListNode(ListNode * node,int value){
nextNode=node;
data=value;
}
};分析:时间复杂度是线性的,可以接受,并且可以顺便找到第一个相交节点,但是却增加了O(length1)的空间复杂度,这显然不能令人满意。——ref:http://www.cnblogs.com/BeyondAnyTime/archive/2012/07/06/2580026.html
方法三:比较尾结点
只要两链表相交,那么相交后的那一段肯定是一样的,也就意味着尾结点是一样的
时间复杂度O(length1 + length2)
寻找尾结点的函数,很简单,就不解释了
/**
寻找尾结点
*/
ListNode * getLastNode(ListNode * head){
if(head==NULL)
return NULL;
while(head->nextNode!=NULL){
head=head->nextNode;
}
return head;
}源代码
#include <stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
/**
1.判断两个【无环】链表是否相交
思路
判断尾节点是否相等
*/
/**
链表结构体
*/
struct ListNode{
int data;
ListNode * nextNode;
ListNode(ListNode * node,int value){
nextNode=node;
data=value;
}
};
ListNode * L1;
ListNode * L2;
//遍历链表
void ScanList(ListNode * node){
while(NULL!=node){
cout<<node->data<<endl;
node = node->nextNode;
}
}
/**
寻找尾结点
*/
ListNode * getLastNode(ListNode * head){
if(head==NULL)
return NULL;
while(head->nextNode!=NULL){
head=head->nextNode;
}
return head;
}
//测试无环相交
void testCross(){
ListNode * node = new ListNode(NULL,0);
node = new ListNode(node,1);
node = new ListNode(node,2);
L1 = new ListNode(node,11);
L1 = new ListNode(L1,12);
L1 = new ListNode(L1,13);
L2 = new ListNode(node,21);
L2 = new ListNode(L2,22);
L2 = new ListNode(L2,23);
}
//测试无环不相交
void testNotCross(){
L1 = new ListNode(NULL,11);
L1 = new ListNode(L1,12);
L1 = new ListNode(L1,13);
L2 = new ListNode(NULL,21);
L2 = new ListNode(L2,22);
L2 = new ListNode(L2,23);
}
void main()
{
testCross();
//testNotCross();
ListNode * node1 = getLastNode(L1);
ListNode * node2 = getLastNode(L2);
if(node1==node2)
cout<<"相交"<<endl;
else
cout<<"不相交"<<endl;
system("pause");
}
原文地址:http://blog.csdn.net/hzy38324/article/details/45285783