标签:节点 alt ble stat toc 编写 info 技术 tin
编写一个程序,找到两个单链表相交的起始节点。
试题链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
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;
}
测试结果:
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;
}
测试结果:
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;
}
测试结果:
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;
}
测试结果:
标签:节点 alt ble stat toc 编写 info 技术 tin
原文地址:https://www.cnblogs.com/xgp123/p/12397561.html