题目描述

输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)

代码:

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }*/
  9. public class Solution {
  10. public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
  11. int len1 = getListNodeLength(pHead1);
  12. int len2 = getListNodeLength(pHead2);
  13. int diff = Math.abs(len1 - len2);
  14. while (diff > 0) {
  15. if (len1 > len2) {
  16. pHead1 = pHead1.next;
  17. } else {
  18. pHead2 = pHead2.next;
  19. }
  20. diff--;
  21. }
  22. while (pHead1 != pHead2
  23. && pHead1 != null
  24. && pHead2 != null) {
  25. pHead1 = pHead1.next;
  26. pHead2 = pHead2.next;
  27. }
  28. return pHead1;
  29. }
  30. private int getListNodeLength(ListNode head) {
  31. int length = 0;
  32. while (head != null) {
  33. length += 1;
  34. head = head.next;
  35. }
  36. return length;
  37. }
  38. }