《leetCode》:Intersection of Two Linked Lists
2016-03-17 21:54
344 查看
题目
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 begin to intersect at node c1. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory.
思路
这个题目就是找两个链表的公共节点,比较简单,自己也碰到过很多次,思路见代码,这里不再描述。struct ListNode { int val; struct ListNode *next; }; int getListLen(struct ListNode *head){ if(head==NULL){ return 0; } struct ListNode *cur=head; int len=0; while(cur!=NULL){ len++; cur=cur->next; } return len; } struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { if(headA==NULL||headB==NULL){ return NULL; } //计算出链表A、B的长度差 int listALen=getListLen(headA); int listBLen=getListLen(headB); struct ListNode *curLargeList=NULL; struct ListNode *curLowList=NULL; int dif=0; if(listALen>=listBLen){//注意:等号如果不写,下面这个if要写 dif=listALen-listBLen; curLargeList=headA; curLowList=headB; } if(listALen<listBLen){ dif=listBLen-listALen; curLargeList=headB; curLowList=headA; } while(dif>0){ curLargeList=curLargeList->next; dif--; } while(curLargeList!=curLowList){ curLargeList=curLargeList->next; curLowList=curLowList->next; } return curLargeList; }
相关文章推荐
- 用户口令复杂度策略设置<<银河麒麟>>
- HDOJ 1254 推箱子【bfs && dfs】
- MOOC《Linux内核分析》第四课
- linux c/c++网络编程----select模型
- Rust 中包访问策略和module开发策略
- 练习脚本三:日志清除
- IOS APP 上传到AppStore
- uva 414 Machined Surfaces
- Python list、tuple、dict区别
- 【2011集训队出题】Crash的数字表格
- VMWare 12 序列号/注册机
- 第三周项目10-小学生计算题的随机生成
- IMMNotificationClient interface(MSDN理解)
- 20.ELK实时日志分析平台之Elasticsearch 查询简介
- OC中的字典NSDictionary
- 练习脚本二:批量添加用户
- 任务三:三栏式布局
- Python:OS 模块 -- 进程管理
- win10下apache不能正常启动的解决方案之一
- VPCS不能通过dhcp协议在win server下获取ip地址的验证性试验