mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
面试题02.07.链表相交:增加C语言实现
This commit is contained in:
@ -249,6 +249,45 @@ var getIntersectionNode = function(headA, headB) {
|
||||
};
|
||||
```
|
||||
|
||||
C:
|
||||
|
||||
```c
|
||||
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
|
||||
ListNode *l = NULL, *s = NULL;
|
||||
int lenA = 0, lenB = 0, gap = 0;
|
||||
// 求出两个链表的长度
|
||||
s = headA;
|
||||
while (s) {
|
||||
lenA ++;
|
||||
s = s->next;
|
||||
}
|
||||
s = headB;
|
||||
while (s) {
|
||||
lenB ++;
|
||||
s = s->next;
|
||||
}
|
||||
|
||||
// 求出两个链表长度差
|
||||
if (lenA > lenB) {
|
||||
l = headA, s = headB;
|
||||
gap = lenA - lenB;
|
||||
} else {
|
||||
l = headB, s = headA;
|
||||
gap = lenB - lenA;
|
||||
}
|
||||
|
||||
// 尾部对齐
|
||||
while (gap--) l = l->next;
|
||||
// 移动,并检查是否有相同的元素
|
||||
while (l) {
|
||||
if (l == s) return l;
|
||||
l = l->next, s = s->next;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user