王道书P40 T8(单链表实现)

/**
 * 用链表实现 王道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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值