7.判断俩个单向链表是否相交

第7 题

微软亚院之编程判断俩个链表是否相交

给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。

为了简化问题,我们假设俩个链表均不带环。

问题扩展:

1.如果链表可能有环列?

2.如果需要求出俩个链表相交的第一个节点列?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

struct node {
int value;
node *next;
};

/**
* 是否有环
*/
bool check(node* head) {
if (head == NULL)
return false;
node *low = head, *fast = head -> next;
while (fast != NULL && fast -> next != NULL) {
low = low -> next;
fast = fast -> next -> next;
if(low == fast)
return true;
}
return false;
}

/**
* 获取尾结点
*/
node* lastNode(node* head) {
if (head == NULL)
return NULL;
node* node = head;
while (node -> next != NULL) {
node = node -> next;
}
return node;
}


int main() {
node *p1, *p2, *p2_2;
p2_2 = (node*) malloc(sizeof(node));
p2 -> value = 22;
p2_2 -> next = NULL;
p1 = (node*) malloc(sizeof(node));
p1 -> value = 1;
p1 -> next = p2_2;
p2 = (node*) malloc(sizeof(node));
p2 -> value = 2;
p2 -> next = p2_2;
if (check(p1) || check(p2)) { // 有环
while (p1 != p2 && p1 != NULL && p2 != NULL) {
p1 = p1->next;
if (p2->next)
p2 = p2->next->next;
else
p2 = p2->next;
}
if (p1 == p2 && p1 && p2)
printf("相交");
else
printf("不相交");
} else { // 无环
if (lastNode(p1) == lastNode(p2))
printf("相交");
else
printf("不相交");
}
printf("\nPress any key to end");
getch();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值