160. Intersection of Two Linked Lists
Posted wangyufeiaichiyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了160. Intersection of Two Linked Lists相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/intersection-of-two-linked-lists/
解题思路:
两个链表的公共节点,首先让长的链表先走length1-length2步,然后一起走
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode 4 * int val; 5 * ListNode next; 6 * ListNode(int x) 7 * val = x; 8 * next = null; 9 * 10 * 11 */ 12 public class Solution 13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) 14 15 int lengthA= getlength(headA); 16 int lengthB = getlength(headB); 17 18 19 if(lengthA>lengthB) 20 21 for(int i=0;i<lengthA-lengthB;i++) 22 23 headA = headA.next; 24 25 26 else 27 28 for(int i=0;i<lengthB-lengthA;i++) 29 30 headB = headB.next; 31 32 33 34 while(headA!=headB) 35 36 headA=headA.next; 37 headB = headB.next; 38 39 return headA; 40 41 public int getlength(ListNode node1) 42 43 int length=0; 44 45 while(node1!=null) 46 47 length++; 48 node1=node1.next; 49 50 return length; 51 52
以上是关于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 Listseasy