鏈表OJ_【返回鏈表的中間結點】【合併鏈表】【刪除倒數n節點】

給定一個帶有頭結點 head 的非空單鏈表,返回鏈表的中間結點。
如果有兩個中間結點,則返回第二個中間結點。

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode qick = head;
        ListNode slow = qick;
       while(qick!=null&&qick.next!=null){
           qick = qick.next.next;
           slow = slow.next;
       }
        return slow;
    }
}

給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。

示例:

給定一個鏈表: 1->2->3->4->5, 和 n = 2.

當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.

鏈接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
       if(head==null){
           return head;
       }
        ListNode slow = head;
        ListNode qick = head;
        for(int i=0;i<n+1;i++){
            if(qick==null){
                return head.next;
            }
            qick = qick.next;
        }
        while(qick!=null){
            qick = qick.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}

將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode header = new ListNode(-1);
        ListNode cur = header;
        while(l1!=null&&l2!=null){
            if(l1.val>l2.val){
                cur.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }else{
               cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            }
            
        }
        if(l1==null&&l2!=null){
                cur.next = l2;
            }
            if(l2==null&&l1!=null){
                cur.next = l1;
            }
        return header.next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章