LeetCode - 19. Remove Nth Node From End of List
2016-07-05 20:46
316 查看
一个比较容易想到的方法就是使用two-pass,第一遍找到Linked List的长度,继而找到从前面看应该删除第几个Node。但是题目的要求是使用one-pass,那么就要使用two pointers了,首先让fast pointer跑到从前面看第n + 1个node的位置,然后同时移动(注意都是从dummyNode开始移动)slow和fast pointer,这时当fast为null的时候,slow就是从后向前的第n - 1个node,这时直接slow.next = slow.next.next即可。注意由于第一个node可能被删除,所以要使用dummyNode。有一个很清晰的图片解释如下:
![](https://img-blog.csdn.net/20160705205147478)
代码如下:/**
* 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) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode slow = dummyNode, fast = dummyNode;
// Move fast in front so that the gap between slow and fast becomes n
for(int i = 0; i <= n; i++){
fast = fast.next;
}
// Move fast to the end, maintaining the gap
while(fast != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}
}
知识点:
1. dummyNode的使用
2. Linked List中two pointer
代码如下:/**
* 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) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode slow = dummyNode, fast = dummyNode;
// Move fast in front so that the gap between slow and fast becomes n
for(int i = 0; i <= n; i++){
fast = fast.next;
}
// Move fast to the end, maintaining the gap
while(fast != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}
}
知识点:
1. dummyNode的使用
2. Linked List中two pointer
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解