【Leetcode】之Remove Nth Node From End of List
2015-11-06 10:09
453 查看
一.问题描述
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.
二.我的解题思路
这道题目的要求根明确,就是仅遍历整个链表一次,然后完成对其中倒数第n个元素的删除。为了满足整个链表只能遍历一次的要求,需要设立3个指针,当遍历结束时候有:一个指向尾节点,一个指向要删除的节点,一个指向要删除的节点的前一个节点。测试通过的程序如下:/** * 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 * p0,* p1,* p2; p0=p1=p2=head; for(int i=0;i<n-1;i++){ p2=p2->next; } if(p2->next==NULL){ if(n==1) return NULL; if(n>1) return head->next; } while(p2->next!=NULL){ p2=p2->next; p0=p1; p1=p1->next; } p0->next=p1->next; return head; } };
相关文章推荐
- Nodejs+Grunt配置SASS项目自动编译
- 通读cheerio API ——NodeJs中的jquery
- 【node.js】本地模式安装express:'express' 不是内部或外部命令,也不是可运行的程序或批处理文件。
- win系统下nodejs安装及环境配置
- Ubuntu环境下sublime3 nodejs安装与插件配置
- nodejs相关--hexo搭建github博客
- 七天学会NodeJS
- Reverse Nodes in k-Group 解答
- nodejs中Unexpected identifier异常
- 【leetcode】Populating Next Right Pointers in Each Node
- windows下使用WebSocket-Node搭建WebSocket服务器
- monodevelop 格式对齐 怎么设置?
- MonoDevelop代码提示前有个P、C、E。这些标志都代表什么?
- 《node.js开发指南》读书笔记(一)
- 将node作为服务器的几种方式
- LeetCode 024 Swap Nodes in Pairs
- [Leetcode]Swap Nodes in Pairs
- win系统下nodejs安装及环境配置
- nodejs+npmjs+express安装配置
- Swap Nodes in Pairs 解答