160. Intersection of Two Linked Lists

安稳与你 提交于 2020-02-25 12:39:53

题目链接: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 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!