160.leetcode Intersection of Two Linked Lists(easy)[链表 公共节点]
来源:互联网 发布:软件魔方怎么卸载 编辑:程序博客网 时间:2024/05/18 23:15
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.
题目的含义是要查找两个链表公共部分的起始位置,可以这样做:首先分别遍历两个链表得到链表的长度,然后得到长度的差,较长的那个链表先多走长度差的长度,然后按照每次往前走一步的方式分别遍历各自对应的链表,当当前节点的值相同时停止返回当前的节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA == NULL ||headB == NULL) return NULL; ListNode* p = headA; ListNode* q= headB; if(p == q) return p; //采用的思想是先计算两个链表的长度,长的先走,然后就同时往后走,找到第一个相等的next int len1 = 0,len2 = 0; while(p!= NULL ) { ++len1; p = p->next; } while(q!= NULL ) { ++len2; q = q->next; } p = headA; q = headB; if(len1>len2) { int dis = len1-len2; while(dis--) p = p->next; }else if(len2>len1) { int dis = len2-len1; while(dis--) q = q->next; } while(p != NULL && q != NULL) { if(p == q) return p; p = p->next; q = q->next; } return NULL; }};
0 0
- 160.leetcode Intersection of Two Linked Lists(easy)[链表 公共节点]
- Leetcode 160. Intersection of Two Linked Lists (Easy) (cpp)
- 【LeetCode】160.Intersection of Two Linked Lists(Easy)解题报告
- leetcode 160. Intersection of Two Linked Lists 链表公共节点
- 160. Intersection of Two Linked Lists (Easy)
- [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
- [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
- 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
- LeetCode-160.Intersection of Two Linked Lists
- 给图片添加水印图片
- 学习IOS的第五天
- 拓扑排序
- Spring源码剖析——核心IOC容器原理
- Effective Java 学习笔记(四、五)
- 160.leetcode Intersection of Two Linked Lists(easy)[链表 公共节点]
- SpringMVC使用注解配置AOP
- 多线程-互斥锁
- 利用jQuery中的val()属性完成默认登陆框
- uva11419 SAM I AM
- 从源码角度分析嵌套滑动机制NestedScrolling
- 关于打开应用白屏或黑屏后进入引导页的问题
- Incorrect string value: '\xF0\x9F\x91\x93\xF0\x9F...' for column 'xxx' at row 1
- MySQL表分区(3)哈希分区-hash