首页 > 其他 > 详细

链表系列编程题

时间:2020-09-13 21:43:20      阅读:64      评论:0      收藏:0      [点我收藏+]

1.判断链表中是否有环

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!=null){           
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast) return true;
        }
        return false;        
    }
}

2.归并有序链表

    public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode curr = head;
        while(l1!=null && l2!=null){
            if(l1.val>l2.val){
                curr.next = l2;
                l2 = l2.next;
            }else{
                curr.next = l1;
                l1 = l1.next;
            }
            curr = curr.next;
        }
        curr.next=l1==null?l2:l1;
        return head.next;    
    }
}

 

链表系列编程题

原文:https://www.cnblogs.com/augenstern/p/13662674.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!