LeetCode OJ刷题历程——Remove Nth Node From End of List
2016-03-06 14:12
549 查看
Given a linked list, remove the nth node from the end of list and return its head. 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.
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) { ListNode *p,*q,*r; int count = 0; r = p = q = head; while(p->next){ p = p->next; if(count>=n-1) q = q->next; if(count>=n) r = r->next; count++; } if(count == 0) head = NULL; else if(r == q) head = head->next; r->next = q->next; q->next = NULL; return head; } };这里只使用了一次遍历,p指针开始遍历,q指针相对于p延迟n-1个时间开始遍历,用以得到倒数第n个结点位置,而r指针用以得到倒数第n+1个结点位置,用以删除操作。
这个题目同样需要注意特殊情况,如链表只有一个结点的情况,应该返回NULL
Given nums = [2, 7, 11, 15], target = 9,Because nums[0]
+ nums[1]
= 2 + 7 = 9,return [0,
1].
相关文章推荐
- 安装node.js,解决ionic安装
- Node.js模块封装及使用方法
- lintcode-easy-Remove Nth Node from End of List
- Node.js模块封装及使用
- Node基础篇(文件操作)
- Node基础篇(模块和NPM)
- Node基础篇(概要)
- Node.js程序中的本地文件操作用法小结
- Node.js模块封装及使用方法
- 让nodejs应用后台执行:forever
- node.js定时事务node-schedule
- LightOJ1257 Farthest Nodes in a Tree (II)(树的点分治)
- 一个由INode节点爆满引起的业务故障 推荐
- [nodejs] nodejs开发个人博客(一)准备工作
- Node初学者入门,一本全面的NodeJS教程
- 25. Reverse Nodes in k-Group
- Permission denied user=hadoop access=WRITE inode=root rootsupergroup rwxr
- Node.Js
- 前端学习总结(八)NodeJS——前端工程师通向后端的里程碑
- Node.js编程快餐(2) - 处理命令行参数