[Leetcode 160] Intersection of Two Linked Lists
2015-07-27 09:51
465 查看
题目
给定两个链表,求两个单链表的交点。要求时间复杂度为O(n),空间复杂度为O(1)
分析
代码
采用方法二/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getLength(ListNode* head){ int length = 0; while(head){ length++; head = head->next; } return length; } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA==NULL || headB==NULL){ return NULL; } int lenA = getLength(headA); int lenB = getLength(headB); if(lenA >= lenB){ for(int i=lenA-lenB; i>0; headA=headA->next,i--) ; }else{ for(int i=lenB-lenA; i>0; headB=headB->next,i--) ; } for(; headA && headB && headA!=headB; headA=headA->next, headB=headB->next) ; return (headA==headB)?headA:NULL; } };
相关文章推荐
- 数据库导入到PowerDesigner中
- Android开发之文件命名规范
- 内存管理之堆和栈的区别
- hdu4403A very hard Aoshu problem 线段树
- Android性能优化:谈话Bitmap内存管理和优化
- LeetCode Swap Nodes in Pairs 交换结点对(单链表)
- JPA criteria 查询:类型安全与面向对象
- poj解题报告——2386
- ORACLE日期时间函数大全
- Android——开发框架的使用说明
- leetCode 92.Reverse Linked List II (反转链表II) 解题思路和方法
- LeetCode 之 Merge Sorted Array(排序)
- 【数据结构】3、模拟银行窗口排队叫号系统——C++
- 安卓工程的目录结构
- a simple hello world nginx module
- IFTTT 加入开源大家庭,已开源5个项目
- Hadoop系统操作类FileSystem
- 29个你必须知道的Linux命令
- 1015. Reversible Primes (20)
- 51单片机学习笔记【九】——红外通信实验