19 Remove Nth Node From End of List
2015-08-25 17:15
525 查看
题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
题目:
解题思路:
这题是很经典的求链表中倒数第 k 个结点问题。以前在《编程之美》里见过。
这题的思路是,维护两个指针,它们之间相差 k 个结点,当前面那个结点到达链表尾时,后面那个指针正好到达倒数第 k 个结点的前驱结点。
用题目中的例子做个解释。
第一个指针从头结点开始向后移动 n = 2 个结点,移动到 3。此时第二指针正指向头结点,它们之间相差 2 个结点。然后第一个指针和第二个指针同时向后移动,直至第一个指针指向链表最后一个结点。即,当第一个指针指向 5 时,第二个指针指向 3(倒数第二个结点的前驱)。
需要注意的是,当 n 正好等于链表长度时,第一个指针从头结点开始向后移动 n 个结点后指向了链表最后一个结点的后继,也就是 null。这时可以断定,要删除的结点就是链表第一个结点,只要将头结点的后继返回即可。
注意:
要特别注意特殊的情况。
题目:
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.
解题思路:
这题是很经典的求链表中倒数第 k 个结点问题。以前在《编程之美》里见过。
这题的思路是,维护两个指针,它们之间相差 k 个结点,当前面那个结点到达链表尾时,后面那个指针正好到达倒数第 k 个结点的前驱结点。
用题目中的例子做个解释。
第一个指针从头结点开始向后移动 n = 2 个结点,移动到 3。此时第二指针正指向头结点,它们之间相差 2 个结点。然后第一个指针和第二个指针同时向后移动,直至第一个指针指向链表最后一个结点。即,当第一个指针指向 5 时,第二个指针指向 3(倒数第二个结点的前驱)。
需要注意的是,当 n 正好等于链表长度时,第一个指针从头结点开始向后移动 n 个结点后指向了链表最后一个结点的后继,也就是 null。这时可以断定,要删除的结点就是链表第一个结点,只要将头结点的后继返回即可。
注意:
要特别注意特殊的情况。
/** * 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; ListNode tmp = head; while(n -- > 0) tmp = tmp.next; if(tmp == null) return head.next; ListNode k = head; while(tmp.next != null) { tmp = tmp.next; k = k.next; } k.next = k.next.next; return head; } }
207 / 207 test cases passed. Status: Accepted Runtime: 276 ms
相关文章推荐
- Windows 系统下设置Nodejs NPM全局路径
- node.js 初体验
- 为什么我要用 Node.js? 案例逐一介绍
- Compilation error in Node.getTextContent for jdk 6
- struct file_operations 和 struct inode 详解
- Nodejs 环境安装
- Nodemanager Out of heap memory[fix bug全过程]
- nodejs日志管理log4js
- nodejs 中的 NODE_PATH
- nodejs安装:nodejs入门
- Using up all the the free Inodes
- 后端分布式系列:分布式存储-HDFS NameNode 设计实现解析
- 后端分布式系列:分布式存储-HDFS NameNode 设计实现解析
- 后端分布式系列:分布式存储-HDFS NameNode 设计实现解析
- HDFS NameNode 设计实现解析
- CCNode扩展,适应MMO的复杂UI逻辑
- node.js(三)url处理
- node.js 基础学习笔记2
- [237] Delete Node in a Linked List
- node.js 基础学习笔记1