[剑指offer]删除链表中倒数第N个节点

19.删除链表中倒数第N个节点

19.删除链表中倒数第N个节点

解题思路1:

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

解题思路2:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode tmp = new ListNode(0, head);
        int len = 0;
        while(tmp.next != null){
            len++;
            tmp = tmp.next;
        }
        ListNode node = new ListNode(0, head);
        int count = 1;
        while(true){
            if(n == len){
                node.next = head.next;
                break;
            }else if(count == len - n){
                head.next = head.next.next;
                break;
            }
            head = head.next;
            count++;
        }
        return node.next;
    }
}

**22.链表中倒数第k个节点 **

22.链表中倒数第k个节点

解题思路1: 快慢指针 让快指针先走k步, 当fast != null时, slow指针刚好指向链表中倒数第k个节点

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

解题思路2: 遍历链表, 统计链表的长度count 链表中倒数第k个节点 = 从头开始遍历count - k + 1个节点处

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null && head.next == null){
            return head;
        }
        int count = 0;
        ListNode p = head;
        while(p.next != null){
            count++;
            p = p.next;
        }
        for(int i = 1; i <= count - k + 1; i++){
            head = head.next;
        }
        return head;
    }
}

已有 0 条评论

    感谢参与互动!