LeetCode——019
2016-04-16 10:24
375 查看
/*
19. Remove Nth Node From End of List My Submissions QuestionEditorial Solution
Total Accepted: 104327 Total Submissions: 355590 Difficulty: Easy
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.
Subscribe to see which companies asked this question
*/
/*
解题思路:
1.我们要删除单链表中的一个元素(在不变动其值得情况下),我们只能是先找到它的前一个节点,然后重新连接。在这里为了防止删除的是正数第一个节点,所以我们有必要加一个临时的头结点dummy。
2.采用快慢指针的思路,去定位倒数第n个节点。两个游标指针fast,slow。先让fast走n步,然后二者同时往下走。最终slow走到要删除节点的前一个元素,而fast走向NULL。
3.执行删除操作。返回dummy->next.
*/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { //使用快慢指针确定倒数第n个元素 ListNode* dummy=new ListNode(-1); dummy->next=head; ListNode* fast=head,*slow=dummy,*pre=dummy; for(int i=0;i<n;i++){ fast=fast->next; } while(fast){ fast=fast->next; slow=slow->next; } fast=slow->next; slow->next=fast->next; delete(fast); return dummy->next; } };
相关文章推荐
- HTML页面关键词随机分布布局
- keil中如何生成bin文件
- SCVMM 2012 SP1 – QuickStart deployment guide
- windows下一分钟配置ngnix实现HLS m3u8点播
- java中日期时间格式与毫秒数的转换
- mysql约束中遇到的一些奇葩版本问题
- 10.--多态、instanceof、内部类、设计模式
- Fragment的生命周期,以及各个回调函数
- 第三方图表库UUChart的简单使用
- SAP 库存关联表信息
- static作用
- objective-c 的方法(method)
- Dubbo高级篇_11_dubbo服务只订阅(开发调试)
- 2016腾讯春招软件研发实习笔试
- DebugLog 打印方法执行时间
- LeetCode 182 -Duplicate Emails ( MYSQL )
- 谓词的使用(predicate)
- 专注95后 “友加”打造最受年轻人喜爱的交友社区
- Configuration类的用法
- 【POI2003/2004 stage I】