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.

    思路:快慢指针。注意代码鲁棒性。时间复杂度O(n),空间复杂度O(1)

    相关题目:《剑指offer》面试题15 

     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     if (head == NULL || n <= 0) return head;
    13     ListNode *pfast = head;
    14     for (int i = 1; i < n; ++i) {
    15         if (pfast == NULL) break; //这是为了k的值大于链表节点总数的情况,本题不存在这种情况
    16         pfast = pfast->next;
    17     }
    18     ListNode **pslow = &head;
    19     while (pfast->next != NULL) {
    20         pfast = pfast->next;
    21         pslow = &((*pslow)->next);
    22     }
    23     
    24     ListNode *q = *pslow;
    25     *pslow = q->next;
    26     delete q;
    27     
    28     return head;
    29 }
    30 };
  • 相关阅读:
    面试题_day0212
    面试题_day0211
    猫眼的数字解密
    缺口验证码
    mysql替换字段里面的内容
    mysql重复id删除
    追踪你的女朋友。
    淘宝登录验证
    jadx-gui-1.0.0.jar怎么运行?
    Python实现一个进度条
  • 原文地址:https://www.cnblogs.com/vincently/p/4060009.html
Copyright © 2011-2022 走看看