leetcode19.删除链表的倒数第N个节点

题目链接:

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

先用粗糙的思路秒了

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode temp = head;
        ListNode ans = head;
        int count = 0;
        //如果链表长度是0或者1,返回空
        if(head == null || head.next == null) return null;
        while(temp != null){
            temp = temp.next;
            count++;
        }
        //如果删除的是head节点,直接返回head.next
        if(count == n) return head.next;
        //是中间节点或者末尾,就用ans来处理
        while(count - n - 1 > 0){
            count--;
            ans = ans.next;
        }
        ans.next = ans.next.next;
        return head;
    }
}

思路就是先扫一遍链表记录链表长度,将链表长度为0或者1,或者删除节点为首的特殊情况写出,一般情况再扫一次链表去掉对应节点。

看了一下官方题解,方法二使用栈(正好学习一下Java怎么使用栈的)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode cur = dummy;
        Deque<ListNode> stack = new LinkedList<ListNode>();
        
        //把每个节点都存进栈里
        while(cur != null){
            stack.push(cur);
            cur = cur.next;
        }
        for( int i = 0; i < n; ++i){
            stack.pop();
        }
        ListNode temp = stack.peek();
        temp.next = temp.next.next;
        dummy = dummy.next;
        return dummy;
    }
}

方法三:双指针

思路很秀啊,慢指针跟快指针保持n的距离,当快指针到达终点的时候慢指针就是要删除的元素的位置,自己手写了一遍,一次过QAQ

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode fast = dummy;
        ListNode slow = dummy;
        if(head == null || head.next == null) return null;
        while(n > 0){
            fast = fast.next;
            n--;
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        dummy = dummy.next;
        return dummy;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值