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;   
        }
    }
    
  • 相关阅读:
    Java中静态字段和静态方法
    Java抽象方法、抽象类以及接口
    Java单例模式
    java继承
    java构造方法
    java方法
    Java常量与变量
    Java初识
    1
    补码,反码,加减法运算,类型取值范围
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14512357.html
Copyright © 2011-2022 走看看