leetcode 160. 相交链表
题目描述
160. 相交链表 - 力扣(LeetCode)
面试题 02.07. 链表相交 - 力扣(LeetCode)
代码:
先计算两个链表的长度。假如长度差是diff。然后让遍历较长的那个链表的指针往前走diff步。然后让遍历两个链表的指针一起往前走,每走一步判断这两个节点是否是同一个节点。
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {int lenA = 0;int lenB = 0;ListNode* pA = headA;while(pA){lenA++;pA = pA->next;}ListNode* pB = headB;while(pB){lenB++;pB = pB->next;}pA = headA;pB = headB;if(lenA >= lenB){int temp = lenA-lenB;while(temp--){pA = pA->next;}}else{int temp = lenB - lenA;while(temp--){pB = pB->next;}}while( pA != pB){pA=pA->next;pB=pB->next;}return pA;}
};