zoukankan      html  css  js  c++  java
  • 19.1.29 [LeetCode 19] Remove Nth Node From End of List

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

    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.

    Follow up:

    Could you do this in one pass?

     1 class Solution {
     2 public:
     3     ListNode* removeNthFromEnd(ListNode* head, int n) {
     4         ListNode hh(0);
     5         hh.next = head;
     6         ListNode*hhead = &hh;
     7         ListNode*first = hhead, *second = hhead->next->next;
     8         int count = 0;
     9         while (head) {
    10             count++;
    11             if (count >= n+1) {
    12                 first = first->next;
    13                 second = second->next;
    14             }
    15             if (head->next == NULL) {
    16                 first->next = second;
    17                 break;
    18             }
    19             head = head->next;
    20         }
    21         return hhead->next;
    22     }
    23 };
    View Code
    注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
  • 相关阅读:
    NSIS制作安装程序
    poj_1011木棒
    hdoj_1312Red and Black
    搜索题目推荐及解题报告
    应届生就职前要读的几本书
    poj_1564Sum It Up
    priority_queue用法
    hdoj_2952Counting Sheep
    poj_1154LETTERS
    poj_2362
  • 原文地址:https://www.cnblogs.com/yalphait/p/10333443.html
Copyright © 2011-2022 走看看