【LeetCode OJ】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.

 1 struct ListNode {
 2     int val;
 3     ListNode *next;
 4     ListNode(int x) : val(x), next(NULL) {}
 5     
 6 };
 7 ListNode *removeNthFromEnd(ListNode *head, int n)
 8 {
 9     ListNode *r = head, *s;
10     if (head == NULL)
11         return head;
12     int i = 0;
13     for (ListNode *p = head; p != NULL; p = p->next)
14     {
15         i++; 
16     }
17     if (i == n)  //删除第一个节点
18     {
19         ListNode *l = head->next;
20         free(head);
21         return l;
22     }
23     for (int num = 0; num < i - n - 1; num++)//找到要删节点的前一个节点
24     {
25         r = r->next;
26     }
27     ListNode *tmp = r->next;
28     r->next = r->next->next;
29     free(tmp);
30     return head;
31     
32 }

 

posted @ 2015-03-31 14:54  温布利往事  阅读(325)  评论(0编辑  收藏  举报