Remove Nth Node From End of List
来源:互联网 发布:淘宝win10激活码木马 编辑:程序博客网 时间:2024/06/06 01:03
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.
思路:两个指针,先走n+1步,因为要获得前面一个node,然后fast slow一起走,注意,fast!=null, fast = fast.next,最后指向的是最后一个node,而不是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 null; int len = 0; ListNode node = head; while(node!=null){ node = node.next; len++; } if(n == len) return head.next; if(n > len) return head; ListNode slow = head; ListNode fast = head; int step = n; while(step > 0){ fast = fast.next; step--; } while(fast!= null && fast.next!=null){ slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return head; } }
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Java 线程池
- hdu4081(最小生成树变形)
- g++编译
- Flash调用WebService实例(最简单的)
- JAVA中使用JSONObject对象
- Remove Nth Node From End of List
- myeclipse svn地址
- HDU 2488 A Knight's Journey(深搜)
- webots仿真机器人平台
- The Importance of Excel
- cpu结构研究
- Good vs Bad Leader
- 根据网页文件夹结构自动生成CHM帮助文件
- java写的zip压缩和解压缩程序