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 };
  • 相关阅读:
    16--Box2D使用(二、显示物理世界)
    15--Box2D使用(一、创建物理世界)
    14--物理引擎Box2D
    13--游戏存档
    12--使用背景音乐
    11--瓦片地图(一)简单实用
    border
    LESS
    jquery Ajax
    解决跨域访问
  • 原文地址:https://www.cnblogs.com/vincently/p/4060009.html
Copyright © 2011-2022 走看看