50-37

mac2022-06-30  96

50题 第37天 相交链表

编写一个程序,找到两个单链表相交的起始节点。链接: 力扣.我的代码如下: /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null||headB==null) { return null; } int lengthA=0; int lengthB=0; ListNode node1=headA; ListNode node2=headB; ListNode result=null; while(node1!=null) { lengthA++; node1=node1.next; } while(node2!=null) { lengthB++; node2=node2.next; } node1=headA; node2=headB; while(lengthA>lengthB) { node1=node1.next; lengthA--; } while(lengthA<lengthB) { node2=node2.next; lengthB--; } while(true) { if(node1==node2) { result=node1; break; } if(node1==null||node2==null) { break; } node1=node1.next; node2=node2.next; } return result; } }

运行结果

和上次的环形链表一样,实现正确的操作,是解决问题的关键。首先我们对两个链表统计长度,然后把长的链表的前面部分截掉,使两个链表长度相同。然后从头依次移动指针,知道出现重合,返回对应的node值,如果遍历整个链表都没有找到,就说媒两个链表没有交错,返回null。
最新回复(0)