标签:Node val next 链表 Leecode curB longList curA C语言
找到两个单链表相交的起始节点。
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;
}
标签:Node,val,next,链表,Leecode,curB,longList,curA,C语言 来源: https://blog.csdn.net/zhungcheng31/article/details/111769547
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。