标签:leetcode
https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
http://fisherlei.blogspot.com/2012/12/leetcode-remove-nth-node-from-end-of.html
/** * 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) { // Soluton A // return removeNthFromEnd_TwoPointer(head, n); // Solution B return removeNthFromEnd_Size(head, n); } ///////////////////////////// // Solution A: 2 Pointers // // Use 2 pointers. // 1. Iterate first pointer to N. // 2. Iterate both first and second pointers until first pointer is null. // At this time, the second pointer is pointing to Nth to the end. private ListNode removeNthFromEnd_TwoPointer(ListNode head, int n) { // Pointer1 to N. ListNode n1 = head; for (int i = 0 ; i < n - 1 ; i ++) { if (n1 == null) return null; // invalid n1 = n1.next; } // Iterate Pointer1 and Pointer2 at the same time. ListNode n2 = head; ListNode pre = null; while (n1.next != null) { n1 = n1.next; pre = n2; n2 = n2.next; } // Delete n2. // If pre == null, it means we need to delete head. (n2 == head) ListNode next = n2.next; n2.next = null; if (n2 == head) { return next; } else { pre.next = next; return head; } } ///////////////////////////// // Solution B: Get the size first // private ListNode removeNthFromEnd_Size(ListNode head, int n) { // Calculate the size first. if (head == null) return null; int size = 0; ListNode node = head; while (node != null) { size++; node = node.next; } // Validate n is a valid value; if (n > size) return null; // Invalid input int nFromHead = size - 1 - (n - 1); node = head; ListNode pre = null; for (int i = 0 ; i < nFromHead ; i ++) { pre = node; node = node.next; } // Remove node ListNode next = node.next; node.next = null; if (node == head) { return next; } else { pre.next = next; return head; } } }
[LeetCode]19 Remove Nth Node From End of List
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598418