/**
* 用链表实现 王道P40 T8
*
* point:
* 跑步案例的思想
*
* ①算法思想:
* 分别计算两个链表的长度,让长的链表先从头移动指针,
* 当移动到两个链表等长时,两个链表的指针同时移动,有公共节点时返回节点位置。
*
* ②数据结构:
* typedef struct LNode{
char data;
struct LNode *next;
}LNode,*LinkList;
*
* ③算法设计
*/
#include <stdio.h>
#include <iostream>
typedef struct LNode{
int data;
struct LNode* next;
}LNode,*LinkList;
//带头结点的传入L -> next,不带头结点的传入 L
int GetLength(LinkList L){
int count = 0;
while(L){
count ++;
L = L -> next;
}
return count;
}
LinkList Common(LinkList str1,LinkList str2){
int l1 = GetLength(str1 -> next);
int l2 = GetLength(str2 -> next);
while(l1 != l2){
if(l1 > l2){
str1 = str1 -> next;
l1--;
}else if(l2 > l1){
str2 = str2 -> next;
l2--;
}
}
//当l1 == l2 时,同时起跑
while(str1 != str2){
str1 = str1 -> next;
str2 = str2 -> next;
}
//当A == B,说明找到了公共节点
return str1;//或者return str2;
}
王道书P40 T8(单链表实现)
于 2022-07-06 15:06:44 首次发布