LeetCode之Intersection of two linked list不同方法

来源:互联网 发布:js显示display 编辑:程序博客网 时间:2024/05/23 19:16

AC完看答案发现答案超简单,而自己的方法有点过于复杂了,题目原意是找出两个链表第一个公共节点,如果没有则返回NULL。

看到题目后,我竟然想到可能存在交叉结构,结果通过反转一个链表来求出是否存在公共节点,但是却没法求出第一个公共节点,因此重新看回题目,发现根本不可能有交叉结构嘛,这是链表啊,一个节点怎么可能有多个next节点呢,两个链表如果有公共节点,其尾节点必然相同。不过,既然已经写了那么多了,那就顺着反转链表的方法继续往下写吧,其实我们只要知道了某个链表是从第几个节点开始进入公共结构就行了呗,所以这里我用了x1代表A链表非公共部分长度,y代表公共部分长度,x2代表B链表非公共部分长度,那么一开始我们可以知道A,B链表的长度,分别位alen=x1+y, blen=x2+y。然后反转A链表后,我们可以从B链表头结点开始遍历得到x1+x2的长度,设这个为rlen,那么x2=(blen-alen+rlen)/2,最后再遍历一遍B链表即可得到第一个公共节点。代码如下:

class Solution {public:    ListNode* reverseList(ListNode* head){        if(!head||!head->next)            return head;        ListNode* node=head,*last=NULL;        while(node){            ListNode* tmp=node->next;            node->next=last;            last=node;            node=tmp;        }        return last;    }    int getLength(ListNode* head){        ListNode* node=head;        int count=0;        while(node){            count++;            node=node->next;        }        return count;    }    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        if(!headA||!headB)            return NULL;        int bLen=getLength(headB),aLen=getLength(headA);        ListNode* aLast=reverseList(headA);        ListNode* node=headB;        while(node->next){            node=node->next;        }        if(node!=headA){            reverseList(aLast);            return NULL;        }        int reverseLen=getLength(headB);        int x2=(reverseLen+bLen-aLen)/2;        reverseList(aLast);        int count=0;        node=headB;        while(node&&count<x2){            node=node->next;            count++;        }        return node;    }};
想的确实太复杂了,不过可以锻炼自己反转链表的代码速度,也是值得的,希望对大家有帮助。

0 0