剑指offer 37. 两个链表的第一个公共结点

xiaoxiao2021-02-27  333

class ListNode { int data; ListNode next; } //题目:找到两个链表的第一个公共结点 public class Main { public static void main(String[] args) throws Exception { ListNode node1 = new ListNode(); ListNode node2 = new ListNode(); ListNode n1 = new ListNode(); ListNode n2 = new ListNode(); ListNode n3 = new ListNode(); ListNode n4 = new ListNode(); ListNode n5 = new ListNode(); node1.next = n1; n1.next = n2; n2.next = n4; n4.next = n5; node2.next = n3; n3.next = n4; node1.data = 1; node2.data = 4; n1.data = 2; n2.data = 3; n3.data = 5; n4.data = 6; n5.data = 7; System.out.println(findFirstCommonNode(node1, node2)); } public static ListNode findFirstCommonNode(ListNode node1, ListNode node2){ int length1 = getLength(node1); int length2 = getLength(node2); int diff = Math.abs(length1-length2); if(length1>length2){ //计算出长度差diff后,将较长的链表先向后走diff步 while(diff>0){ node1 = node1.next; diff--; } }else{ while(diff>0){ node2 = node2.next; diff--; } } while(node1!=null && node2!=null){ if(node1 == node2){ return node1; } node1 = node1.next; node2 = node2.next; } return null; } public static int getLength(ListNode node){ //计算链表的总长度 int result = 0; while(node!=null){ result++; node = node.next; } return result; } }
转载请注明原文地址: https://www.6miu.com/read-1480.html

最新回复(0)