zoukankan      html  css  js  c++  java
  • leetcode: Remove Nth Node From End of List

    http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

    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.

    思路

    两个指针p1和p2,令p2先走N - 1步,然后两个指针一起往前走,每一步保存当前的p1为prev,当p2->next为NULL时,p1就是要删除的那个节点,另prev->next = p1->next。实现的时候比较偷懒,没有考虑输入head为NULL和n为0的情况。

     1 class Solution {
     2 public:
     3     ListNode *removeNthFromEnd(ListNode *head, int n) {
     4         ListNode *l1 = head, *l2 = head, *prev = NULL;
     5         
     6         for (int i = 1; i < n; ++i) {
     7             l2 = l2->next;
     8         }
     9         
    10         while (true) {
    11             if (NULL == l2->next) {
    12                 break;
    13             }
    14             
    15             prev = l1;
    16             l1 = l1->next;
    17             l2 = l2->next;
    18         }
    19         
    20         if (prev != NULL) {
    21             prev->next = l1->next;
    22             return head;
    23         }
    24         else {
    25             return l1->next;
    26         }
    27     }
    28 };
  • 相关阅读:
    uva11021
    WC2019退役失败记
    北大集训2018垫底记
    NOI后训练记录
    NOI2018垫底记
    NOI前训练记录
    JSOI2018R2游(afo)记
    HNOI(AHOI)2018游记
    JSOI2018R1(九省联考)游(afo)记
    LR 8 Hello 戊戌
  • 原文地址:https://www.cnblogs.com/panda_lin/p/remove_nth_node_from_end_of_list.html
Copyright © 2011-2022 走看看