LeetCode -- Remove Nth Node from End of List
2015-09-09 19:26
543 查看
Question:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
Analysis:
给出一个链表,移走从链表的末尾数起第n个节点,然后返回原来链表的链首。注意:n一般来说是有效的,尝试只遍历链表一次解决问题。
首先遍历一遍链表,得出链表的总长度。然后删除从最末数的第n个节点,也就是删除从头结点数起的第len+1-n个节点,这样,只需找到第len-n个节点,然后删除他后面的一个节点即可。注意只有一个节点而且n=1的情况;删除首节点的情况;删除最后节点的情况等。
Answer:
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.
Analysis:
给出一个链表,移走从链表的末尾数起第n个节点,然后返回原来链表的链首。注意:n一般来说是有效的,尝试只遍历链表一次解决问题。
首先遍历一遍链表,得出链表的总长度。然后删除从最末数的第n个节点,也就是删除从头结点数起的第len+1-n个节点,这样,只需找到第len-n个节点,然后删除他后面的一个节点即可。注意只有一个节点而且n=1的情况;删除首节点的情况;删除最后节点的情况等。
Answer:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return head; if(n <= 0) return head; //先得到链表的长度 int len = 1; ListNode h = head; while(h.next != null) { h = h.next; len++; } if(n == 1 && head.next == null) //只有一个节点的情况 return null; if(n == 1) { //删除最后一个节点 h = head; while(h.next.next != null) { h = h.next; } h.next = null; return head; } if(n == len) { //删除第一个节点 h = head; head = head.next; h.next = null; return head; } int del = len - n; h = head; int i = 1; while(i < del) { h = h.next; i++; } h.next = h.next.next; return head; } }
相关文章推荐
- Nodejs课堂笔记-第二课 package.json的作用
- 【前端学习笔记】2015-09-09~~~~nodejs中的require()和module.exports
- UVa 10223 - How many nodes ?
- 使用nvm进行node多版本管理
- GDataXMLNode配置
- chef client注册为node
- Node.js进程通信模块child_process
- 有 JavaScript 基础,怎么学习 Node.js
- Node-RSA 验证签名
- Node.js 4.0正式发布,支持ES6新特性
- Node.js 4.0.0 正式发布了
- NodeJs API
- hexo异常:/usr/bin/env: node: 没有那个文件或目录
- Nodejs课堂笔记—第一课:修改Webstorm的默认主题
- leetcode - Swap Nodes in Pairs
- LeetCode Count Complete Tree Nodes
- LeetCode Count Complete Tree Nodes
- nodejs 笔记
- node.js url模块
- node.js 基础学习笔记3 -express