leetcode-160 Intersection of Two Linked Lists
2015-04-15 10:11
288 查看
剑指offer上的题目,自己的比较挫的代码
比较屌的做法(concise clean nice elegant)
<span style="font-family:Microsoft YaHei;font-size:14px;">/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA == NULL || headB == NULL) return NULL; int lenA = 0,lenB = 0; ListNode *workA = headA,*workB = headB; lenA = lenList(headA); lenB = lenList(headB); if(lenA > lenB){ int gap = lenA - lenB; while(gap){ workA = workA->next; gap--; } }else if(lenA < lenB){ int gap = lenB - lenA; while(gap){ workB = workB->next; gap--; } } while(workA != workB){ workA = workA->next; workB = workB->next; } return workA; } int lenList(ListNode *node){ int len = 0; while(node){ len++; node = node->next; } return len; } };</span>
比较屌的做法(concise clean nice elegant)
<span style="font-family:Microsoft YaHei;font-size:14px;">/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA == NULL || headB == NULL) return NULL; ListNode *workA = headA,*workB = headB; while(workA != NULL && workB != NULL && workA != workB){ workA =workA->next; workB = workB->next; if(workA == workB) return workA; if(workA == NULL) workA = headB; if(workB == NULL) workB = headA; } return workA; } };</span>
相关文章推荐
- leetcode 160 Intersection of Two Linked Lists C++
- leetcode 160 Intersection of Two Linked Lists
- [Leetcode 160] Intersection of Two Linked Lists
- leetcode 160:Intersection of Two Linked Lists
- Leetcode 160 Intersection of Two Linked Lists
- LeetCode 160 : Intersection of Two Linked Lists (Java)
- [leetcode]#160 Intersection of Two Linked Lists
- Java for LeetCode 160 Intersection of Two Linked Lists
- leetcode 160 Intersection of Two Linked Lists
- leetcode 160: Intersection of Two Linked Lists
- leetcode 160: Intersection of Two Linked Lists
- leetcode-Intersection of Two Linked Lists-160
- [LeetCode160]Intersection of Two Linked Lists
- LeetCode 160 Intersection of Two Linked Lists
- 【LeetCode 160】Intersection of Two Linked Lists
- leetcode_c++:链表:Intersection of Two Linked Lists(160)
- leetcode[160] Intersection of Two Linked Lists
- LeetCode 160:Intersection of Two Linked Lists
- [LeetCode-160] Intersection of Two Linked Lists(找到两链表公共交叉点)
- leetcode160~Intersection of Two Linked Lists