码迷,mamicode.com
首页 > 其他好文 > 详细

19. Remove Nth Node From End of List

时间:2017-10-13 16:12:06      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:pre   idt   code   com   ini   else   ima   nth node   href   

 

技术分享

 

移除链表中倒数第n个元素

马丹,返回的不是第n个元素,而是移除了元素之后的链表地址。。。。。。

读了十几年书,审题还是这种水平

 

  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(head == NULL || n < 0)            /* linklist is NULL or n is negative */
 10         return NULL;
 11     else {
 12         int len = 0;
 13         struct ListNode* p = head;
 14         while(p != NULL) {        /* get length of linklist */
 15             p=p->next;
 16             len++;
 17         }
 18 
 19         printf("%d\n", len);
 20 
 21         if(n > len)
 22             return NULL;
 23         else {
 24             struct ListNode q, *temp; /* set a empty head as new head */
 25             q.next = head;
 26             p = &q;
 27             while((len-n+1) != 0) {
 28                 len--;
 29                 temp = p;
 30                 p = p->next;
 31             }
 32             temp->next = temp->next->next;
 33             return q.next;
 34         }
 35     }
 36 }

19. Remove Nth Node From End of List

标签:pre   idt   code   com   ini   else   ima   nth node   href   

原文地址:http://www.cnblogs.com/tuhooo/p/7661434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!