Leetcode#19||Remove Nth Node From End of List
2015-08-12 12:17
615 查看
/**
* 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 || n <= 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
for (int i = 1; i <= n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
* 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 || n <= 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
for (int i = 1; i <= n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
相关文章推荐
- [LeetCode] Partition List
- [LeetCode] Next Permutation
- [LeetCode]Copy List with Random Pointer
- [LeetCode]Reverse Linked List
- [LeetCode] Remove Element
- [LeetCode] Linked List Cycle
- [LeetCode] Merge Sorted Array
- [LeetCode] Merge Two Sorted Lists
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Swap Nodes in Pairs
- [LeetCode] 3Sum Closest
- [LeetCode] 3Sum
- [leetCode] Minimum Size Subarray Sum
- [leetCode] Merge Sorted Array
- Reverse Linked List II
- Add Two Numbers
- Partition List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Rotate List