链表系列编程题

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;    
    }
}

 3.返回链表的倒数第k个节点:

暴力法:

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        ListNode count = head;
        int length = 0;
        while(count!=null){
            count = count.next;
            length++;           
        }
        if(k>length) return null;
        int i = length - k;
        ListNode curr = head;
        while(i>0){
            curr = curr.next;
            i--;           
        }
        return curr;
    }
}

快慢指针法:

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
       ListNode slow = head;
       ListNode fast = head;
       for(int i=1;i<=k;i++){
           if(fast==null)
                return null;
           fast = fast.next;
       }
        while(fast!=null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

 

posted @ 2020-09-13 19:18  菅兮徽音  阅读(206)  评论(0)    收藏  举报