剑指offer-day12
合并两个排序的链表
还是双指针的题目,一开始是想直接在两个链表上处理的,后来发现会出现漏元素的问题,就跟着答案老老实实地用一条新链表来接。
思路很简单,用两个指针p和q遍历两个链表,p<=q时将p指向的元素放入新建的链表,反之则放入q指向的元素,遍历至一个指针遍历完成,将新链表指向未遍历完的那个指针就完成了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null){ return l2; } if(l2 == null){ return l1; } ListNode p = l1; ListNode q = l2; ListNode head = new ListNode(-1); ListNode pre = head; while(p != null && q != null){ if(p.val <= q.val){ ListNode cp = p; head.next = cp; head = head.next; p = p.next; } else{ ListNode cq = q; head.next = cq; head = head.next; q = q.next; } } if(p != null){ head.next = p; } if(q != null){ head.next = q; } return pre.next; } }
|
两个链表的第一个公共节点
这个并没有想出来怎么做,还是看答案吧。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){ return null; } ListNode p = headA; ListNode q = headB; while(p != q){ if(p == null){ p = headB; } else{ p = p.next; } if(q == null){ q = headA; } else{ q = q.next; } } return p; } }
|