• Remove Nth Node From End of List


    1. Problem

     去掉链表的倒数第n个节点,并返回链表头。一次遍历完成

    Given a linked list, remove the nth node from the end of list and return its head.
    
    For example,
    
       Given linked list: 1->2->3->4->5, and n = 2.
    
       After removing the second node from the end, the linked list becomes 1->2->3->5.
    Note:
    Given n will always be valid.
    Try to do this in one pass.

    2. Solution

    用两个指针:

    • p:指向可能的待删节点的前一个节点;
    • q:q-p = n;

    为了方便处理,在链表前加上一个空节点。代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode removeNthFromEnd(ListNode head, int n) {
    11         if( head == null )
    12             return head;
    13         //create a new head node so that we can always remove p.next
    14         ListNode newHead = new ListNode(0);
    15         newHead.next = head;
    16         ListNode p = newHead;   //point to the previous node before to-be-deleted node
    17         ListNode q = head;  //q - p = n;
    18         int count = 1;  //to find the first satisfied q;
    19         for( ; q.next!=null && count<n; count++, q = q.next);
    20         //the to-be-deleted node exists
    21         if(count == n ){
    22             while( q.next != null ){
    23                 p = p.next;
    24                 q = q.next;
    25             }
    26             p.next = p.next.next;
    27         }
    28         return newHead.next;
    29     }
    30 }
  • 相关阅读:
    pip 安装
    「csp模拟」模拟测试15
    某些博客的优化
    晚间测试6
    「csp模拟」模拟测试15
    「csp模拟」模拟测试14
    线段树维护单调栈
    晚间测试 2
    晚间测试 1
    晚间测试4
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4668690.html
Copyright © 2020-2023  润新知