19. Remove Nth Node From End of List
来源:互联网 发布:下载中文ae软件 编辑:程序博客网 时间:2024/05/29 15:05
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.
死办法。。 有一点要注意, 见下面注释
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { int cnt = 0; int flag = 0; ListNode* p = head; if(!head) return NULL; if(head->next == NULL && n == 1) return NULL; while(head) { cnt++; head = head->next; } ListNode* q = p; while(q) { flag++; if(n == 1) //这里是判断,如果删除的是尾结点,操作会不一样,而且也没有NEXT,直接写next就错了 { if(flag ==(cnt - n)) q->next = NULL; } else if(flag == (cnt - n + 1)) { q->val = q->next->val; q->next = q->next->next; break; } q = q->next; } return p; }};
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode dum(0), *slow=&dum, *fast=head; dum.next=head; //get the dum connected // move the fast pointer according to the offset for(int i=0; i<n; ++i) fast=fast->next; while(fast) { fast=fast->next; slow=slow->next; } //now the slow pointer will be the n+1 th node from the end (may be the dum head) fast=slow->next; slow->next=fast->next; delete fast; //remove the specified node return dum.next; }};
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- java中String、StringBuffer、StringBuilder的区别
- 待总结
- 最大流
- CSS+JS+Java设计12306登录界面
- CSS3自定义滚动条样式 -webkit-scrollbar
- 19. Remove Nth Node From End of List
- YII2伪静态(路由配置)
- C++11 多线程并发1
- Java - Java子类继承父类并调用接口
- java的动态代理机制详解--20
- 【SCOI 2005】王室联邦 树上分块?
- 事件模块
- eclipse中struts2 hibernate jar包位置
- c语言数据结构之顺序表单循环链表的创建及功能函数