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