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 };
  • 相关阅读:
    WCF实现上传图片功能
    C#中String.Empty、NULL与""三者的区别
    C#中equal与==的区别
    static 关键字的使用,静态和非静态类的区别
    C#索引器
    C# 接口的隐式与显示实现说明
    Python文件处理
    Python3.X与urllib
    python中if __name__ == '__main__'
    Python中的random模块
  • 原文地址:https://www.cnblogs.com/chkkch/p/2770033.html
Copyright © 2011-2022 走看看