Remove Nth Node From End of List
2015-12-27 22:51
761 查看
每日算法——leetcode系列
问题 Remove Nth Node From End of List
Difficulty: EasyGiven 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.
/** * 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个节点
难度系数:简单给定一个链表,从链表末尾删除第n个节点并返回链表
例如:
给定链表: 1->2->3->4->5, and n = 2。 从尾部删除第二个节点后,此链表变为 1->2->3->5。
注意:
给定的n总是有效的
试着一次遍历解决问题
思路
此题关键点在于找到从尾部数的第n个节点,由于是单向链表,并且题目要求是一次遍历,肯定有一个取巧的办法。定理:最后一个节点到从尾部数的第n个节点相差为n(废话!)
维护双指针,让第一个指针先走n步,这时候第二个指针和第一个指针相差n步,再同时移动两个指针,这样这两个指针一直相差n步,当第一个节点指向尾部是,第二个节点就是要打的从尾部数第n个节点
代码
class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (head == nullptr || n <= 0) { return nullptr; } ListNode tempHead(-1); tempHead.next = head; head = &tempHead; ListNode *p1 = head, *p2 = head; for (int i = 0; i < n; ++i) { if (p1 == nullptr){ return nullptr; } p1 = p1->next; } while (p1->next != nullptr) { p1 = p1->next; p2 = p2->next; } p2->next = p2->next->next; return head->next; } };
相关文章推荐
- node.js之打包工具webpack
- 省时的浏览器同步测试工具browser-sync服务搭建
- LeetCode-19-Remove Nth Node From End of List(链表)-Easy
- nodejs的N个tip
- React Native + Nodejs 使用RSA加密登录
- 使用Angular和Nodejs搭建聊天室
- [leetcode] 237. Delete Node in a Linked List 解题报告
- 【实践】nodeJS写个简单的爬虫程序
- leetcode - Populating Next Right Pointers in Each Node II
- nodejs+chromium 创建桌面应用程序
- hadoop namenode ha--手动切换
- nodejs npm常用命令
- 用node开发repl应用
- Yum安装nodejs + npm之CetnOS 6.5
- nodejs认证模块passport.js参数解释
- Node.js and Forever “exited with code: 0”
- Node.js and Forever “exited with code: 0”
- Node.js and Forever “exited with code: 0”
- Node.js and Forever “exited with code: 0”
- 填坑系列: nodejs后台在支付宝异步通知时获取到的参数为空(使用koa模块)