赞
踩
方法:
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
- struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
- int lenA = 0, lenB = 0;
- struct ListNode* curA = headA, *curB = headB;
-
- while(curA != NULL)
- {
- lenA++;
- curA = curA->next;
- }
- while(curB != NULL)
- {
- lenB++;
- curB = curB->next;
- }
-
- struct ListNode* longList = headA;
- struct ListNode* shortList = headB;
-
- int dis = lenA - lenB;
-
- if(lenA < lenB)
- {
- longList = headB;
- shortList = headA;
- dis = -dis;
- }
-
- struct ListNode* longCur = longList;
- struct ListNode* shortCur = shortList;
-
- while(dis--)
- {
- longCur = longCur->next;
- }
-
- while(longCur != NULL && shortCur != NULL)
- {
- if(longCur == shortCur)
- {
- return longCur;
- }
- longCur = longCur->next;
- shortCur = shortCur->next;
- }
- return NULL;
- }
思路:
如果两个链表相交,那么从交点之后它们的节点都相同。如果想求出交点,可以先遍历两个链表求出它们的长度。求出长度差。然后创建两个指针分别指向两个链表的头节点,之后让长链表先走长度差步,此时两个指针同时走,并且每走一步都要比较指向的节点是否是同一个节点,如果是,则返回节点,遍历完之后则返回空。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。