leetcode019 Remove Nth Node From End of List
2016-04-02 00:43
495 查看
题目
19. Remove Nth Node From End of ListGiven 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计算要删除的元素的位置,再遍历到该位置,将它删除。注意如果是第一个的话要特殊处理。代码:
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode tmp = head; int length = 0; while(tmp != null) { length++; tmp = tmp.next; } int pos = length - n + 1; tmp = head; if(pos == 1) return head.next; int i = 1; while(tmp != null) { if(++i == pos) { tmp.next = tmp.next.next; break; } tmp = tmp.next; } return head; }
结果细节(图):
相关文章推荐
- NodeJS、NPM安装配置步骤(windows版本)
- node.js环境搭建——helloworld
- Ubuntu里node命令无效解决方法
- node.js Stream
- node-firefox 二三事
- node-firefox 二三事
- 基于Node.js的微服务后台
- (转)如何制作nodejs,npm “绿色”安装包
- node.js开发中使用Node Supervisor实现监测文件修改并自动重启应用
- LintCode "Swap Two Nodes in Linked List"
- nodejs笔记四--创建一个最简单的 express 应用
- (OK) 交叉编译node-v4.2.1—for—android
- Node初学者入门,一本全面的NodeJS教程(转载)
- Add Two Numbers(OC版)
- Hadoop获取namenode的命令
- leetcode 25 -- Reverse Nodes in k-Group
- Aggregation is not enabled. Try the nodemanager at xingyunfei001.com.cn:50800
- hadood2.6.0启动datanode报错
- LeetCode 24. Swap Nodes in Pairs
- 好厉害的库edge.js!实现C#与node.js互操作