首页 > 代码库 > [LeetCode]19 Remove Nth Node From End of List
[LeetCode]19 Remove Nth Node From End of List
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。