本文主要是介绍leetcode:(160) Insertion of Two Linked List(java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package LeetCode_LinkedList;/*** 题目:* Write a program to find the node at which the intersection of two singly linked lists begins.* 解题思路:* 首先定义两个nodeA,nodeB分别从链表A,链表B的头部开始遍历,当nodeA遍历到A的末尾时,nodeA从链表B的头部开始遍历,* 当nodeB遍历到链表B末尾时,nodeB从链表A的头部开始遍历,当nodeA和nodeB相等的时候,即为两个链表交集的第一个节点。*/ public class GetIntersectionNode_160_1017 {public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {if (headA == null || headB == null) {return null;}ListNode nodeA = headA;ListNode nodeB = headB;while (nodeA != nodeB) {nodeA = nodeA == null ? headB : nodeA.next;//nodeA为空时,从链表B开始遍历nodeB = nodeB == null ? headA : nodeB.next;//nodeB为空时,从链表A开始遍历}return nodeA;}//主函数进行测试public static void main(String[] args) {ListNode node1 = new ListNode(1);ListNode node3 = new ListNode(3);ListNode node4 = new ListNode(5);ListNode node5 = new ListNode(7);ListNode node6 = new ListNode(9);ListNode node7 = new ListNode(11);node1.next = node3;node3.next = node4;node4.next = node5;node5.next = node6;node6.next = node7;ListNode node2 = new ListNode(2);ListNode node8 = new ListNode(4);node2.next = node8;node8.next = node6;GetIntersectionNode_160_1017 test = new GetIntersectionNode_160_1017();ListNode result = test.GetIntersectionNode(node1, node2);System.out.println(result.val);} }
这篇关于leetcode:(160) Insertion of Two Linked List(java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!