/** * 题目: * 输入两个链表,找出它们的第一个公共结点。 * 解题思路: * 首先求出两个链表的长度,获得两个链表的长度差differ, * 在第二次遍历时,长链表先走differ步,然后同时遍历两个链表, * 找到第一个相同的节点就是他们的第一个公共节点。 */ public class P253_FirstCommonNodeBetweenTwoLinkedlists { public ListNode FirstCommonNodeBwtweenLinkedlists(ListNode pHead1, ListNode pHead2) { ListNode result = null; if (pHead1 == null || pHead2 == null) { return result; } //分别求出两个链表的长度 int length1 = GetLength(pHead1); int length2 = GetLength(pHead2); ListNode longList = null; ListNode shortList = null; //找出pHead1和pHead2哪个是长链表、短链表 if (length1 > length2) { longList = pHead1; shortList = pHead2; } else { longList = pHead2; shortList = pHead1; } //求出两个链表的长度差,并让长链表先走differ步 int differ = Math.abs(length1 - length2); for (int i = 0; i < differ; i++) { longList = longList.next; } //同时遍历两个链表,寻找第一个相同的节点 while (longList != null && shortList != null) { if (longList == shortList) { result = longList; break; } else { longList = longList.next; shortList = shortList.next; } } return result; } public int GetLength(ListNode pHead) { if (pHead == null) { return 0; } int count = 0; ListNode node = pHead; while (node != null) { count++; node = node.next; } return count; } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode node5 = new ListNode(5); ListNode node6 = new ListNode(6); ListNode node7 = new ListNode(7); node1.next = node2; node2.next = node3; node3.next = node6; node6.next = node7; node4.next = node5; node5.next = node6; P253_FirstCommonNodeBetweenTwoLinkedlists test = new P253_FirstCommonNodeBetweenTwoLinkedlists(); ListNode result = test.FirstCommonNodeBwtweenLinkedlists(node1, node4); System.out.println(result.val); } }
剑指offer:两个链表的第一个公共节点(java)
猜你喜欢
转载自blog.csdn.net/Sunshine_liang1/article/details/82863391
今日推荐
周排行