【Leetcode】Remove Nth Node From End of List
2015-11-19 19:46
579 查看
题目链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
题目:
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.
思路:
1、先求链表长度,遍历链表找到要删除结点需要的指针,需要遍历两遍。
2、用两个指针,两指针距离为n,并且每次移动一步,直到表尾,此时前一个指针指向的就是倒数第n个结点
算法1:
算法2:
算法3:
考虑上面的算法需要考虑到如果删除的是表头,需要单独处理,经常在别人的题解中见到头结点可以将表头当普通结点一样操作,简化程序。
下面的代码就是加了头结点。
题目:
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.
思路:
1、先求链表长度,遍历链表找到要删除结点需要的指针,需要遍历两遍。
2、用两个指针,两指针距离为n,并且每次移动一步,直到表尾,此时前一个指针指向的就是倒数第n个结点
算法1:
public int getListLength(ListNode head) { int length = 0; ListNode p = head; while (p != null) { length++; p = p.next; } return length; } public ListNode removeNthFromEnd(ListNode head, int n) { int length = getListLength(head); ListNode pre = null, p = head; int i = length - n + 1;// 正序移动距离 while (--i > 0) {// 获取要删除节点的指针 pre = p; p = p.next; } if (pre != null) { pre.next = p.next; } else { head = p.next;// 当删除头节点时 } return head; }
算法2:
public ListNode removeNthFromEnd(ListNode head, int n) { // nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p ListNode p = head, nth = head, pre = null; while (--n > 0) { p = p.next; } while (p.next != null) { p = p.next; pre = nth; nth = nth.next; } // 此时p指向表尾,nth指向倒数n个结点 if(pre==null){ //如果删除的是头结点 head = nth.next; }else{ pre.next = nth.next; } return head; }
算法3:
考虑上面的算法需要考虑到如果删除的是表头,需要单独处理,经常在别人的题解中见到头结点可以将表头当普通结点一样操作,简化程序。
下面的代码就是加了头结点。
public ListNode removeNthFromEnd(ListNode head, int n) { // nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p ListNode newHead = new ListNode(0);// 头结点 ListNode p = head, nth = head, pre = newHead; newHead.next = head; while (--n > 0) { p = p.next; } while (p.next != null) { p = p.next; pre = nth; nth = nth.next; } // 此时p指向表尾,nth指向倒数n个结点 pre.next = nth.next; return newHead.next; }
相关文章推荐
- Hadoop NameNode元数据相关文件目录解析
- node.js中的控制台
- delete node_modules dir in windows
- Node.js框架之express
- 基于html5和nodejs相结合实现websocket即使通讯
- Node初学者入门,一本全面的NodeJS教程(推荐阅读)
- 浅析nodejs实现Websocket的数据接收与发送
- Node.js中使用socket创建私聊和公聊聊天室
- nodejs
- 详解nodejs中使用socket的私聊和公聊的办法
- nodejs express template (模版)的使用 (ejs + express)
- node的“宏任务(macro-task)”和“微任务(micro-task)”机制
- Nodejs express创建应用
- nodes 验证码
- Node.js开发框架Express4.x
- easyui:Cannot read property 'nodeName' of null问题的解决
- nodejs express 获取请求信息的方法
- Node.js中使用socket创建私聊和公聊聊天室
- 浅析nodejs实现Websocket的数据接收与发送
- 基于html5和nodejs相结合实现websocket即使通讯