Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
c1 → c2 → c3
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
}
题目大意
写一个程序,找出两个单链表开始相交的节点。
难度系数:容易
实现
int getListLen(ListNode* node)
{
int cnt = 0;
while (node) {
cnt++;
node = node->next;
}
return cnt;
}
ListNode* seekListNode(ListNode* node, int offset)
{
while (offset--) {
node = node->next;
}
return node;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL)
return NULL;
int lenA = getListLen(headA);
int lenB = getListLen(headB);
ListNode* tempNodeA = NULL;
ListNode* tempNodeB = NULL;
if (lenA > lenB) {
tempNodeA = seekListNode(headA, lenA - lenB);
} else {
tempNodeB = seekListNode(headB, lenB - lenA);
}
for (; tempNodeA != NULL; tempNodeA = tempNodeA->next, tempNodeB = tempNodeB->next) {
if (tempNodeA == tempNodeB)
return tempNodeA;
}
return NULL;
}
我想,这个实现是满足要求的,我看别人也是这个思路,但我不知道为什么效率上,好多人都比我的快???
时间: 2024-11-10 08:29:08