zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    依然是双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *removeNthFromEnd(ListNode *head, int n) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (head == NULL)
    15             return NULL;
    16             
    17         ListNode *pPre = NULL;
    18         ListNode *p = head;
    19         ListNode *q = head;
    20         for(int i = 0; i < n - 1; i++)
    21             q = q->next;
    22             
    23         while(q->next)
    24         {
    25             pPre = p;
    26             p = p->next;
    27             q = q->next;
    28         }
    29         
    30         if (pPre == NULL)
    31         {
    32             head = p->next;
    33             delete p;
    34         }
    35         else
    36         {
    37             pPre->next = p->next;
    38             delete p;
    39         }
    40         
    41         return head;
    42     }
    43 };
  • 相关阅读:
    Unity3D启动报错的解决方案
    Unity3D引用dll打包发布的问题及解决
    轻量级C#网络通信组件StriveEngine —— C/S通信开源demo(附源码)
    k8s 各种网络方案
    网络模型
    管理和安装 chart
    开发自己的 chart
    再次实践 MySQL chart
    chart 模板
    chart 目录结构
  • 原文地址:https://www.cnblogs.com/chkkch/p/2770033.html
Copyright © 2011-2022 走看看