LeetCode 19

Posted Juntaran

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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: [email protected]
 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 }

 

以上是关于LeetCode 19的主要内容,如果未能解决你的问题,请参考以下文章

Cg入门19:Fragment shader - 片段级模型动态变色

LeetCode刷题笔记-数据结构-day19

Python代码阅读(第19篇):合并多个字典

Leetcode.1024 视频拼接

android.view.InflateException:二进制 XML 文件第 15 行:二进制 XML 文件第 19 行:膨胀类片段时出错

LeetCode刷题笔记-数据结构-day19