码迷,mamicode.com
首页 > 其他好文 > 详细

两个链表的交叉

时间:2017-07-22 18:20:49      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:==   section   技术   str   link   next   int   src   strong   

代码(C++):

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// write your code here
if (headA == NULL||headB == NULL)
return NULL;
ListNode *p = headA;
ListNode *q = headB;
int a = 1, b = 1;
while (p -> next != NULL) {
p = p -> next;
a += 1;
}
while (q -> next != NULL) {
q = q->next;
b += 1;
}
if (q != p)
return NULL;
if (a > b) {
for (int i = 0; i < a-b; i++) {
headA = headA -> next;
}
} else if (a < b) {
for (int j = 0; j < b-a; j++) {
headB = headB -> next;
}
}
while (headA != headB) {
headA = headA->next;
headB = headB->next;
}
return headA;
}
};

技术分享

两个链表的交叉

标签:==   section   技术   str   link   next   int   src   strong   

原文地址:http://www.cnblogs.com/majixian/p/7221808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!