LeetCode 19

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 }