题目
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
分析
- 由于连个链表的长度不同,没法直接比较,需要移动指针使两个指针分别在两个链表的相同索引处
- 可以使用长度相减法使指针处于相同索引处,也可以使用补齐法使指针处于相同索引处
代码如下
补齐法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *p, *q;
p = headA;
q = headB;
//补齐思想,较短的链表先到达末尾,然后跳到较长链表的头节点,这样就相当于对短链表进行了补齐
while(p != q) {
p = (p ? p->next : headB);
q = (q ? q->next : headA);
}
return p;
}
相减法
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *current_node_a = headA;
struct ListNode *current_node_b = headB;
int length_a = 1;
int length_b = 1;
if (headA == NULL || headB == NULL) return NULL;
while (current_node_a->next != NULL) {
current_node_a = current_node_a->next;
length_a++;
}
while (current_node_b->next != NULL) {
current_node_b = current_node_b->next;
length_b++;
}
current_node_a = headA;
current_node_b = headB;
if (length_a < length_b) {
int temp = length_b - length_a;
while(temp--) current_node_b = current_node_b->next;
}
if (length_a > length_b) {
int temp = length_a - length_b;
while(temp--) current_node_a = current_node_a->next;
}
if (current_node_a == current_node_b) return current_node_a;
while(current_node_a->next != NULL) {
if (current_node_a->next == current_node_b->next) return current_node_a->next;
current_node_a = current_node_a->next;
current_node_b = current_node_b->next;
}
return NULL;
}