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 }
  • 相关阅读:
    js如何引入本地json文件
    python学习笔记(八)———— IO编程
    python学习笔记(七)———— 错误、调试和测试
    接口测试
    cookie和token都存放在header中,为什么不会劫持token?
    占位
    MongoDB和MySql的区别(详细)且会持续补充
    【转】五分钟让你彻底了解TDD、ATDD、BDD&RBE
    python学习笔记(六)————面向对象高级编程
    Fiddler模拟接口数据(mock)(四)
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5511664.html
Copyright © 2011-2022 走看看