leetcode_c++:链表:Intersection of Two Linked Lists(160)
2016-07-18 16:08
429 查看
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
O(N)
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
O(N)
class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { //计算表的长度 int lenA=getListlength(headA); int lenB=getListlength(headB); if(lenA<=0 || lenB<=0) return NULL; if(lenA<lenB) swap(headA,headB); //move head of the listA,make both of Lists are same length for(int i=0;i<abs(lenA-lenB);i++) headA=headA->next; while(headA!=headB){ headA=headA->next; headB=headB->next; } return headA; } private: inline int getListlength(ListNode* head){ int len=0; while(head!=NULL){ head=head->next; len++; } return len; } };
相关文章推荐
- 浅谈C/C++中static extern关键字的作用
- Leetcode 58. Length of Last Word (Easy) (cpp)
- C++拷贝构造函数详解
- C++四种常用的类型转换机制
- MTCNN--《Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks》疑问一大堆
- c++之getopt函数的使用
- C语言_向函数传递结构体信息_plusC14.5
- 快速排序算法C语言
- 【链表】C++链表反转、链表逆序打印
- ROS学习之 cpp服务
- 【C语言入门教程】5.6 函数库和文件
- 【C语言入门教程】5.5 实现问题(效率)
- 【C语言入门教程】5.4 递归
- 【C语言入门教程】5.3 函数的调用 与 参数
- Leetcode 38. Count and Say (Easy) (cpp)
- 【C语言入门教程】5.2 函数的作用域规则(auto, static)
- C++后台实践:古老的CGI与Web开发
- c字符串的一些操作
- C语言范例学习02
- 【C语言入门教程】5.1 函数说明 与 返回值