题目:
输入两个单向链表,找出它们的第一个公共结点
解答:
1 public class Solution { 2 3 4 public static void main(String[] args) { 5 ListNode head1 = new ListNode(); 6 ListNode second1 = new ListNode(); 7 ListNode third1 = new ListNode(); 8 ListNode forth1 = new ListNode(); 9 ListNode fifth1 = new ListNode(); 10 ListNode head2 = new ListNode(); 11 ListNode second2 = new ListNode(); 12 ListNode third2 = new ListNode(); 13 ListNode forth2 = new ListNode(); 14 head1.nextNode = second1; 15 second1.nextNode = third1; 16 third1.nextNode = forth1; 17 forth1.nextNode = fifth1; 18 head2.nextNode = second2; 19 second2.nextNode = forth1; 20 third2.nextNode = fifth1; 21 head1.data = 1; 22 second1.data = 2; 23 third1.data = 3; 24 forth1.data = 6; 25 fifth1.data = 7; 26 head2.data = 4; 27 second2.data = 5; 28 third2.data = 6; 29 forth2.data = 7; 30 System.out.println(findFirstCommonNode(head1,head2).data); 31 32 } 33 34 public static ListNode findFirstCommonNode(ListNode head1, ListNode head2) { 35 int len1 = getListLength(head1); 36 int len2 = getListLength(head2); 37 38 ListNode longListNode = null; 39 ListNode shortListNode = null; 40 41 int diff = 0; 42 if(len1 > len2) { 43 longListNode = head1; 44 shortListNode = head2; 45 diff = len1 - len2; 46 } else { 47 longListNode = head2; 48 shortListNode = head1; 49 diff = len2 - len1; 50 } 51 52 for(int i = 0; i < diff; i++) { 53 longListNode = longListNode.nextNode; 54 } 55 56 while(longListNode != null && shortListNode != null && longListNode != shortListNode) { 57 longListNode = longListNode.nextNode; 58 shortListNode = shortListNode.nextNode; 59 } 60 61 return longListNode; 62 } 63 64 65 66 private static int getListLength(ListNode head) { 67 int result = 0; 68 if(head == null) { 69 return result; 70 } 71 72 ListNode point = head; 73 while(point != null) { 74 point = point.nextNode; 75 result++; 76 } 77 78 return result; 79 } 80 } 81 82 83 public class ListNode { 84 int data; 85 ListNode nextnode; 86 }