题目链接:输入两个链表,找出它们的第一个公共结点。
解题思路:
找出2个链表的长度,然后让长的先走两个链表的长度差,然后再一起走
(因为2个链表用公共的尾部)
1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 public class Solution { 11 public ListNode FindFirstCommonNode(ListNode phead1, ListNode phead2) { 12 13 int head1_length = getlength(phead1); 14 int head2_length = getlength(phead2); 15 16 if(head1_length>=head2_length) 17 { 18 int chazhi = head1_length-head2_length; 19 for(int i=0;i<chazhi;i++) 20 { 21 phead1 = phead1.next; 22 } 23 24 } 25 else if(head1_length<head2_length) 26 { 27 int chazhi = head2_length-head1_length; 28 for(int i=0;i<chazhi;i++) 29 { 30 phead2 = phead2.next; 31 } 32 33 } 34 while(phead1!=phead2) 35 { 36 phead1 = phead1.next; 37 phead2 = phead2.next; 38 } 39 40 return phead1; 41 42 43 } 44 45 public static int getlength(ListNode l1) 46 { 47 int length=0; 48 49 while(l1!=null) 50 { 51 length++; 52 l1=l1.next; 53 } 54 return length; 55 } 56 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10872679.html
时间: 2024-10-09 08:39:25