编程语言
首页 > 编程语言> > 剑指offer - 面试题52: 两个链表的第一个公共节点 - C++

剑指offer - 面试题52: 两个链表的第一个公共节点 - C++

作者:互联网

大概思路我记得。无任何参考写出来了

第一次没通过是我想冒险试一下如何一句话定义两个指针

// 编译错误,提示不能把ListNode*转为 ListNode型
// ListNode *pNode1 = pHead1, pNode2 = pHead2; 
// 正确写法
ListNode *pNode1 = pHead1, *pNode2 = pHead2;

记住咯!

我的代码:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
        int length1 = 0, length2 = 0;
        ListNode * pNode1 = pHead1, * pNode2 = pHead2;
        while(pNode1 != nullptr) {
            length1++;
            pNode1 = pNode1->next;
        }
        while(pNode2 != nullptr) {
            length2++;
            pNode2 = pNode2->next;
        }
        pNode1 = pHead1;
        pNode2 = pHead2;
        if(length1 >= length2) {
            for(int i=0; i<length1-length2; i++) {
                pNode1 = pNode1->next;
            }
        } else {
            for(int i=0; i<length2-length1; i++) {
                pNode2 = pNode2->next;
            }
        }
        while(pNode1 != pNode2) {
            pNode1 = pNode1->next;
            pNode2 = pNode2->next;
        }
        return pNode1;
    }
};

嫌有些地方写了两遍,于是改进,改进后的代码很清沥,而且函数功能单一:

class Solution {
public:
    ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
        int length1 = CountNodes(pHead1), length2 = CountNodes(pHead2);
        ListNode *pNode1 = pHead1, *pNode2 = pHead2;
        if(length1 >= length2) {
            pNode1 = StepForward(pHead1, length1-length2);
        } else {
            pNode2 = StepForward(pHead2, length2-length1);
        }
        while(pNode1 != pNode2) {
            pNode1 = pNode1->next;
            pNode2 = pNode2->next;
        }
        return pNode1;
    }
    int CountNodes(ListNode* pHead) {
        int result = 0;
        ListNode* pNode = pHead;
        while(pNode != nullptr) {
            result++;
            pNode = pNode->next;
        }
        return result;
    }
    ListNode* StepForward(ListNode* pHead, int num) {
        ListNode* pNode = pHead;
        for(int i=0; i<num; i++) {
            if(pNode == nullptr) return nullptr;
            pNode=pNode->next;
        }
        return pNode;
    }
};

夸一下自己现在追究到底的精神!有什么不懂的,当场搞懂,这样积累下来会越来越棒的!

标签:面试题,ListNode,offer,pNode2,pNode1,next,链表,int,pHead1
来源: https://blog.csdn.net/L_bic/article/details/100020052