Easy-题目38:160. Intersection of Two Linked Lists
2016-05-30 20:28
260 查看
题目原文:
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
题目大意:
求两个单链表的交点。
题目分析:
考研数据结构复习的时候见过此题,应该是链表处理的题目中比较经典的一道。解法是求出两个链表的长度,然后两个指针分别指向两个链表的头结点,先让较长的链表的指针走过差值的步数,这样两个指针距离尾节点的距离就相同了,让两个节点并行走直到遇到交点。
源码:(language:c)
成绩:
32ms,beats 18.75%,众数32ms,78.91%
cmershen的碎碎念:
这道题比较经典,但如果不给出这个算法,自己是很难想到的。
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.
题目大意:
求两个单链表的交点。
题目分析:
考研数据结构复习的时候见过此题,应该是链表处理的题目中比较经典的一道。解法是求出两个链表的长度,然后两个指针分别指向两个链表的头结点,先让较长的链表的指针走过差值的步数,这样两个指针距离尾节点的距离就相同了,让两个节点并行走直到遇到交点。
源码:(language:c)
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { if(!headA||!headB) return NULL; struct ListNode *p; int lengtha,lengthb; for(p=headA,lengtha=0;p;p=p->next,lengtha++); for(p=headB,lengthb=0;p;p=p->next,lengthb++); if(lengtha>lengthb) { for(int i=0;i<lengtha-lengthb;i++) headA=headA->next; } else if (lengthb>lengtha) { for(int i=0;i<lengthb-lengtha;i++) headB=headB->next; } while(headA!=headB) { headA=headA->next; headB=headB->next; } return headA; }
成绩:
32ms,beats 18.75%,众数32ms,78.91%
cmershen的碎碎念:
这道题比较经典,但如果不给出这个算法,自己是很难想到的。
相关文章推荐
- 常用docker镜像安装
- MyEclipse10配置自动补全/字体大小/行号/背景颜色
- 求和减2的次方
- poj 2286
- Easy-题目37:111. Minimum Depth of Binary Tree
- QT——2、Hello World
- Android 4000 学习记录(十九)-简单的动画清除
- Easy-题目36:112. Path Sum
- .m 文件与.mm文件的区别
- Java代码实现AP向CP侧发送AT指令
- Easy-题目35:9. Palindrome Number
- 反转链表17
- 2016SDAU课程练习三1013
- 搜集整理java中GC的理解
- java 基于jxl解析xls以及解决丢失精度问题
- mysql 锁表解锁
- 十四周项目-项目3-数组类模板
- 持续集成(上)
- linux学习笔记2 - linux常用命令
- 设计模式学习笔记--迭代器模式