双链表是否重合并返回
/** * 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; ListNode noA = headA; ListNode noB = headB; while(noA != noB){ noA = noA == null? headB : noA.next; noB = noB == null? headA : noB.next; } return noA; } }
说实话代码没啥难度,技巧就是两个指针无论next是否为null,都会给指针赋值,作用:当两指针交换后位置同步时,两链表不重复会null=null也能退出while,还有就是,短链表循环完以后会衔接长链表,先遍历,等长链表结束以后与短链表连接后,开始同步进行

浙公网安备 33010602011771号