Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97766
  • 博文数量: 21
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 200
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-11 22:44
个人简介

HUST16届准毕业生,发奋求职中...

文章分类

全部博文(21)

文章存档

2015年(17)

2014年(4)

我的朋友

分类: C/C++

2015-07-10 00:01:30

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.

解法:删除列表中倒数第n个节点,设置两个节点指针ptr1和ptr2,它们之间相差n个节点,然后将指针往下移动,当ptr2的下一个节点为NULL时,ptr1就指向了删除节点的前一个节点。

特殊情况测试用例:
[1],1
[1,2],1
[1,2],2

C语言实现:

点击(此处)折叠或打开

  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  * int val;
  5.  * struct ListNode *next;
  6.  * };
  7.  */
  8. struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
  9.     if(NULL == head )
  10.         return NULL;
  11.     struct ListNode *ptr1,*ptr2,*tmp = NULL;
  12.     int i;
  13.     ptr1 = head;
  14.     ptr2 = head;
  15.     for(i=0;i<n;i++)
  16.     {
  17.         ptr2 = ptr2->next;
  18.     }
  19.     if(NULL == ptr2)
  20.     {
  21.         tmp = head;
  22.         head = head->next;
  23.         free(tmp);
  24.         return head;
  25.     }
  26.     while(ptr2->next)
  27.     {
  28.         ptr2 = ptr2->next;
  29.         ptr1 = ptr1->next;
  30.     }
  31.     tmp = ptr1->next;
  32.     ptr1->next = (ptr1->next)->next;
  33.     free(tmp);
  34.     return head;
  35. }

阅读(1335) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~