找到两个单链表相交的起始节点。
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//找到两个单链表相交的起始节点。https://leetcode-cn.com/problems/intersection-of-two-linked-lists/description/
typedef struct ListNode{
char val[3];
struct ListNode *next;
}Node;
//方法一:走两遍法
struct ListNode* getIntersectionNode(Node*headA,Node*headB){
struct ListNode* curA = headA;
struct ListNode* curB = headB;
while (curA != curB){
if (curA){
curA = curA->next;
}
else{
curA = headB;
}
if (curB){
curB = curB->next;
}
else{
curB = headA;
}
}
return curB;
}
//方法二: 长链表先走差步 法;
struct ListNode* getIntersectionNode_2(Node*headA, Node*headB){
Node*curA = headA;
Node*curB = headB;
//先计算链表A,B的长度
int La = 0, Lb = 0;
while (curA){
++La;
curA = curA->next;
}
while (curB){
++Lb;
curB = curB->next;
}
//找出长链表和短链表 ;(假设链表A长,B短;)
Node*longList = headA;
Node*shortList = headB;
if (La < Lb){
longList = headB;
shortList = headA;
}
int gap = abs(La - Lb);
while (gap){
longList = longList->next;
gap--;
}
//============================================
while (longList!= shortList){
longList = longList->next;
shortList = shortList->next;
}
//----------上段也可以这么写-----------------
/*while (longList){
if (longList == shortList){
return longList;
}
longList = longList->next;
shortList = shortList->next;
}
return NULL; */
//=============================================
return longList;
}
int main(){
Node*a1 = (Node*)malloc(sizeof(Node));
strcpy(a1->val, "a1"); //a1->val= "a1"; 字符串赋值只能 “strcpy”
Node*a2 = (Node*)malloc(sizeof(Node));
strcpy(a2->val, "a2");
Node*c1 = (Node*)malloc(sizeof(Node));
strcpy(c1->val, "c1");
Node*c2 = (Node*)malloc(sizeof(Node));
strcpy(c2->val, "c2");
Node*c3 = (Node*)malloc(sizeof(Node));
strcpy(c3->val, "c3");
Node*b1 = (Node*)malloc(sizeof(Node));
strcpy(b1->val,"b1");
Node*b2 = (Node*)malloc(sizeof(Node));
strcpy(b2->val , "b2");
//链表1:
a1->next = a2; a2->next = c1; c1->next = c2; c2->next = c3; c3->next = NULL;
//链表2:
b1->next = b2; b2->next = c1; c1->next = c2; c2->next = c3; c3->next = NULL;
//Node*ret = getIntersectionNode(a1, b1);
Node*ret = getIntersectionNode_2(a1, b1); //答案:c1
printf("Reference of the node with value: %s\n", ret->val);
system("pause");
return 0;
}