Remove Nth Node From End of List
2015-12-11 01:02
477 查看
题目:
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.
首先我加了个头指针head1便于处理(这样就不用把只有一个节点,并且要求删除它的情况单独拿出来处理了),然后用两个指针p,q,先让一个指针p先走n步,然后p,q一起运动,直到p.next == null,然后删除q.next即可,具体代码如下:
PS:注意因为题目要求只遍历一遍,所以这样写,但这样写并不会比那种先遍历一遍获取链表长度,然后算出删除的节点是正数第几个,再遍历删除它效率高。
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.
首先我加了个头指针head1便于处理(这样就不用把只有一个节点,并且要求删除它的情况单独拿出来处理了),然后用两个指针p,q,先让一个指针p先走n步,然后p,q一起运动,直到p.next == null,然后删除q.next即可,具体代码如下:
/** * 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) { ListNode head1 = new ListNode(0); head1.next = head; ListNode p = head1,q = head1; for(int i = 0;i < n;i++) { p = p.next; } while(p.next != null) { p = p.next; q = q.next; } p = q.next; q.next = q.next.next; p = null;//提醒Java虚拟机它可以被回收了。。。 return head1.next; } }
PS:注意因为题目要求只遍历一遍,所以这样写,但这样写并不会比那种先遍历一遍获取链表长度,然后算出删除的节点是正数第几个,再遍历删除它效率高。
相关文章推荐
- Insert Node in a Binary Search Tree
- 简述CCNode和Sprite的渲染过程
- hadoop mkdir: Cannot create directory /usr. Name node is in safe mode.
- nodejs 操作文件(文件夹)
- NodeJS 基本操作
- Nodejs源码解析之module
- nodejs入门
- yum node.js
- node.js中模块,require
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- node开发环境搭建(windows)
- 理解Node.js的事件循环
- nodejs项目在webstorm里进行debug的设定
- nodejs获取当前url和url参数值
- NODE 安装express4.X 失败
- node.js入门总结
- wix xslt for adding node
- leetcode:237 Delete Node in a Linked List-每日编程第四题
- nodejs安装及express
- node.js 的stream(流)和模块系