zoukankan      html  css  js  c++  java
  • LeetCode 19

    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.

     1 /*************************************************************************
     2     > File Name: LeetCode019.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: Tue 17 May 2016 15:59:22 PM CST
     6  ************************************************************************/
     7 
     8 /*************************************************************************
     9     
    10     Remove Nth Node From End of List 
    11     
    12     Given a linked list, 
    13     remove the nth node from the end of list and return its head.
    14 
    15     For example,
    16 
    17     Given linked list: 1->2->3->4->5, and n = 2.
    18 
    19     After removing the second node from the end, 
    20     the linked list becomes 1->2->3->5.
    21        
    22     Note:
    23     Given n will always be valid.
    24     Try to do this in one pass.
    25 
    26  ************************************************************************/
    27 
    28 #include <stdio.h>
    29 /**
    30  * Definition for singly-linked list.
    31  * struct ListNode {
    32  *     int val;
    33  *     struct ListNode *next;
    34  * };
    35  */
    36 struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
    37 {
    38     struct ListNode* fast = head;
    39     struct ListNode* slow = head;
    40 
    41     while( n > 0 )
    42     {
    43         fast = fast->next;
    44         n --;
    45     }
    46     if( fast == NULL )
    47     {
    48         free(head);
    49         return head->next;
    50     }
    51     while( fast->next != NULL )
    52     {
    53         fast = fast->next;
    54         slow = slow->next;
    55     }
    56     fast = slow->next;
    57     slow->next = slow->next->next;
    58     free(fast);
    59 
    60     return head;
    61 }
  • 相关阅读:
    docker registry
    2019最新EI源刊目录
    在Asp.net Core中使用中间件来管理websocket
    自定义WPF窗体形状
    Font Awesome矢量版,十六进制版,WPF字体使用
    什么是fortran语言之fortran语言入门
    Java各国首都列表
    世界各国货币,C#数字货币计算
    Ocelot中文文档入门
    F#语言入门之什么是F#语言
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5511664.html
Copyright © 2011-2022 走看看