編寫一個程序,找到兩個單鏈表相交的起始節點。測試
試題連接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/3d
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; }
測試結果:code
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; }
測試結果:blog
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; }
測試結果:leetcode