zoukankan      html  css  js  c++  java
  • 【数据结构】算法 Remove Nth Node From End of List 删除链表的倒数第 N 个结点

    Remove Nth Node From End of List 删除链表的倒数第 N 个结点

    Given the head of a linked list, remove the nth node from the end of the list and return its head.

    输入:head = [1,2,3,4,5], n = 2
    输出:[1,2,3,5]
    

    双指针+虚头

    由于要删除倒数第N个节点,原则上要找到倒数第N+1节点。但是这样处理就会超过一次遍历。

    一次遍历搞定:

    设置p,q 两个指针,p指向虚头,q指向head头结点,q向后走N个节点。如果q不为空的话,此时p,q同时移动,直到q指向null,此时p指向的节点就是那个需要被删除的节点。

    /**
     * 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 ret = new ListNode(0,head),p = ret,q=head;
            int k =n;
            while(k>0){
                q=q.next;
                k--;
            }
            while(q!=null){
                q= q.next;
                p=p.next;
            }
            ListNode tmp = p;
            p.next = p.next.next;
            return ret.next;   
        }
    }
    
  • 相关阅读:
    《研磨设计模式》阅读摘要
    心电图
    nodejs
    自动化测试
    Hook技术
    热修复原理
    理解ClassLoader
    Dalvik和ART
    Java虚拟机
    理解WindowManagerService
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14512357.html
Copyright © 2011-2022 走看看