Java删除链表的倒数第N个结点

Java删除链表的倒数第N个结点,第1张

19. 删除链表的倒数第N个结点

解题思路1:
链表的长度len
删除链表的倒数第N个结点就是删除链表的第len - N个结点


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

解题思路2:
利用先进后出

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        Deque<ListNode> stack = new LinkedList<>();
        ListNode cur = dummy;
        while(cur != null){
            stack.push(cur);
            cur = cur.next;
        }
        for(int i = 0; i < n; i++){
            stack.pop();
        }
        ListNode pre = stack.peek();
        pre.next = pre.next.next;
        return dummy.next;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/723241.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存