160. 相交链表
目录
- 160. 相交链表
- 1、试题介绍
- 2、java做法
- 2.1、双重循环
- 2.2、双指针做法
- 3、C语言做法
- 3.1、双重循环
- 3.2、双指针做法
1、试题介绍
编写一个程序,找到两个单链表相交的起始节点。
试题链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
2、java做法
2.1、双重循环
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
while (headA != null) {
ListNode p = headB;
while (p != null) {
if(headA == p) {
return headA;
}
p = p.next;
}
headA = headA.next;
}
return null;
}
测试结果:
2.2、双指针做法
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode pA = headA;
ListNode pB = headB;
int sizeA = 0;
int sizeB = 0;
while (pA != null || pB != null) {
if(pA != null) {
sizeA++;
pA = pA.next;
}
if(pB != null) {
sizeB++;
pB = pB.next;
}
}
pA = headA;
pB = headB;
if(sizeA > sizeB) {
for(int i = 0;i < sizeA - sizeB;i++) {
pA = pA.next;
}
}else {
for(int i = 0;i < sizeB - sizeA;i++) {
pB = pB.next;
}
}
while (pA != pB ) {
if(pA == null || pB == null) return null;
pA = pA.next;
pB = pB.next;
}
return pA;
}
测试结果:
3、C语言做法
3.1、双重循环
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA == NULL || headB == NULL) return NULL;
while (headA != NULL) {
struct ListNode* p = headB;
while (p != NULL) {
if(headA == p) {
return headA;
}
p = p->next;
}
headA = headA->next;
}
return NULL;
}
测试结果:
3.2、双指针做法
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA == NULL || headB == NULL) return NULL;
struct ListNode* pA = headA;
struct ListNode* pB = headB;
int sizeA = 0;
int sizeB = 0;
while (pA != NULL || pB != NULL) {
if(pA != NULL) {
sizeA++;
pA = pA->next;
}
if(pB != NULL) {
sizeB++;
pB = pB->next;
}
}
pA = headA;
pB = headB;
if(sizeA > sizeB) {
for(int i = 0;i < sizeA - sizeB;i++) {
pA = pA->next;
}
}else {
for(int i = 0;i < sizeB - sizeA;i++) {
pB = pB->next;
}
}
while (pA != pB ) {
if(pA == NULL || pB == NULL) return NULL;
pA = pA->next;
pB = pB->next;
}
return pA;
}
测试结果: