LeetCode Remove Nth Node From End of List
2015-08-29 01:00
357 查看
原题链接在这里:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Method 1: 算出总长度,再减去n,即为要从头多动的点。但要新要求,only one pass。
Method 2: 两个指针,一个runner,一个walker,runner先走n步,随后runner和walker一起走,直到runner指为空。
Note: 1. 都是找到要去掉点的前一个点记为mark,再通过mark.next = mark.next.next去掉对应应去掉的点。
2. 注意去掉list头点的情况,e.g. 1->2, n = 2.
AC Java:
Method 1: 算出总长度,再减去n,即为要从头多动的点。但要新要求,only one pass。
Method 2: 两个指针,一个runner,一个walker,runner先走n步,随后runner和walker一起走,直到runner指为空。
Note: 1. 都是找到要去掉点的前一个点记为mark,再通过mark.next = mark.next.next去掉对应应去掉的点。
2. 注意去掉list头点的情况,e.g. 1->2, n = 2.
AC Java:
/** * 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) { /*Method 1 if(head == null) return head; int len = 0; ListNode temp = head; while(temp != null){ temp = temp.next; len++; } if(len < n){ return head; } int moveNum = len - n; ListNode dunmy = new ListNode(0); dunmy.next = head; temp = dunmy; while(moveNum > 0){ temp = temp.next; moveNum--; } temp.next = temp.next.next; return dunmy.next; */ //Method 2 if(head == null || n == 0) return head; ListNode dunmy = new ListNode(0); dunmy.next = head; ListNode runner = dunmy.next; ListNode walker = dunmy; while(n>0 && runner != null){ runner = runner.next; n--; } while(runner != null){ runner = runner.next; walker = walker.next; } walker.next = walker.next.next; return dunmy.next; } }
相关文章推荐
- LeetCode Remove Nth Node From End of List
- windows下使用Nodejs开发Express4.x
- Remove Nth Node From End of List
- 解读Nodejs多核处理模块cluster
- LeetCode(237) Delete Node in a Linked List
- Node.js进程通信模块child_process
- nodepad++的emmet的使用问题
- NodeJs文件操作备注
- nodejs初步了解
- [leetcode] 19.Remove Nth Node From End of List
- nodejs 处理表单上传文件时,获取不到表单数据
- node.js和websocket实现echo
- 常用NodeJS工具
- 部署node程序并维持正常运行时间
- [刷题]Nth to Last Node in List
- [leetcode] 25.Reverse Nodes in k-Group
- jade模板引擎学习笔记(WebsStorm9.0.3+ nodejs+express+jade)
- NodeJS优缺点及适用场景讨论
- 既然nodejs是单线程的,那么它怎么处理多请求高并发的?
- 基于NodeJS的全栈式开发(基于NodeJS的前后端分离)