Remove Nth Node From End of List
来源:互联网 发布:php 高级算法 编辑:程序博客网 时间:2024/05/16 17:57
Q:
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.
Solution:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null) return null; ListNode fakeHead = new ListNode(0); fakeHead.next = head; ListNode p = head; ListNode q = head; ListNode prev = fakeHead; for (int i = 0; i < n; i++) q = q.next; while (q != null) { q = q.next; p = p.next; prev = prev.next; } prev.next = p.next; return fakeHead.next; }}
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
- Servlet学习
- Rotate List
- lamp架构源码安装
- 手机第三方支付产品安全性
- 【Leetcode】Find Minimum in Rotated Sorted Array II
- Remove Nth Node From End of List
- poj 3356 文本编辑距离
- Maximum Product Subarray
- [Leetcode] Search in Rotated Sorted Array
- PostgreSQL的特性
- USACO Picture 解题报告
- 2014年的双11背后会隐藏什么猫腻?
- 双11背后隐藏的猫腻:商品先提价再做降价促销
- 2014年的双11背后会隐藏什么猫腻?