160. Intersection of Two Linked Lists(Linked List)
来源:互联网 发布:明星代言页游 知乎 编辑:程序博客网 时间:2024/06/03 17:29
Title
Write a program to find the node at which the intersection of two singly linked lists begins.
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.
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==NULL || headB == NULL){ return NULL; } struct ListNode *p, *q, *a, *b; p = headA; a = headA; q = headB; b = headB; while(p!=NULL && q!=NULL){ p = p->next; q = q->next; } while(p != NULL){ a = a->next; p = p->next; } while(q != NULL){ b = b->next; q = q->next; } while(a!=NULL && b!=NULL){ if(a == b){ return a; } a = a->next; b = b->next; } return NULL;}
runtime:37ms
思路:
首先,这个题目是判断两个单链表是否有交叉,如何寻找交叉节点问题
指针p、q分别遍历链表a、b,假设q先到达NULL(即 假设a 比 b 长),此时从a的头发出一个指针t,当p到达NULL时,从b的头发出s,当s==t的时候即交点。
虽然基础,但这个我也是需要借鉴的…至于思路,我就看了下知乎这里,谢谢。
0 0
- 160. Intersection of Two Linked Lists(Linked List)
- 160. Intersection of Two Linked Lists(Linked List-Easy)
- [leetcode][list] Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists leetcode (list)
- LeetCode[Linked List]: 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
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 用SmartUpload实现文件上传
- 5.21pkusc模拟赛5
- execute immediate 运行动态SQL
- 验证码 倒计时
- Java 获取字符串中第N次出现的字符位置
- 160. Intersection of Two Linked Lists(Linked List)
- 图片控件,动画控件
- 简说ES6中的变量定义:let、const
- Eclipse中使用SVN
- Android:ImageView代码设置background和src
- Oracle Database的安装与卸载
- js刷新页面方法大全
- Linux系统终端批量替换文本
- chrome 文件上传路径问题