Remove Nth Node From End of List
2015-07-22 21:26
645 查看
1. Problem
去掉链表的倒数第n个节点,并返回链表头。一次遍历完成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.
2. Solution
用两个指针:p:指向可能的待删节点的前一个节点;
q:q-p = n;
为了方便处理,在链表前加上一个空节点。代码如下:
/** * 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; //create a new head node so that we can always remove p.next ListNode newHead = new ListNode(0); newHead.next = head; ListNode p = newHead; //point to the previous node before to-be-deleted node ListNode q = head; //q - p = n; int count = 1; //to find the first satisfied q; for( ; q.next!=null && count<n; count++, q = q.next); //the to-be-deleted node exists if(count == n ){ while( q.next != null ){ p = p.next; q = q.next; } p.next = p.next.next; } return newHead.next; } }
相关文章推荐
- [leedcode 116] Populating Next Right Pointers in Each Node
- NodeJS开发者-资质分级评判标准
- Populating Next Right Pointers in Each Node II
- HTML DOM nodeName nodeValue
- [leetcode] Reverse Nodes in k-Group
- 使用Node.js+Socket.IO搭建WebSocket实时应用(聊天室)
- node.js 入门示例
- NodeJS中的事件
- datanode却没有启动
- datanode却没有启动
- node.js教程learnyounode 闯关答案
- 【LeetCode】19 Remove Nth Node From End of List (c++实现)
- leetcode Reverse Nodes in k-Group
- leetcode - Delete Node in a Linked List
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- 探秘Node.js(一)——Node.js简介及安装配置
- 使用express4.x版和Jade模板重写《nodejs开发指南》微博实例
- NodeJS 、Express4.x、Jade使用方法
- Node.js的线程和进程
- 基于NodeJS进行前后端分离