当前位置: 代码迷 >> 综合 >> leetcode 160:Intersection of Two Linked Lists
  详细解决方案

leetcode 160:Intersection of Two Linked Lists

热度:45   发布时间:2023-12-18 00:36:39.0

问题描述:

Write a program to find the node at which the intersection of two singly linked lists begins.

思路:

题目说O(n)时间解决问题。求两条list的相交点,可以首先求出两条list的长度差,然后调整使得两个指针同步到达相交点,那么相交点就可以得到。

代码:

class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {int lengthA = 0, lengthB = 0;ListNode *count_p;//count listAcount_p = headA;while (count_p != NULL){lengthA++;count_p = count_p->next;}//count listBcount_p = headB;while (count_p != NULL){lengthB++;count_p = count_p->next;}ListNode *nowA, *nowB;nowA = headA;nowB = headB;//align the two listsint dif = lengthA - lengthB;if (dif < 0)   //listB is longer{for (int i = 0; i < -dif; i++){nowB = nowB->next;}}if (dif > 0)  //listA is longer{for (int i = 0; i < dif; i++){nowA = nowA->next;}}while (nowA != nowB){nowA = nowA->next;nowB = nowB->next;}return nowA;}
};
  相关解决方案