题目:
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.
链接: http://leetcode.com/problems/remove-nth-node-from-end-of-list/
题解:
one pass remove Nth node from the end。要建立一个dummy node,用来记录所要移除节点之前的节点,再利用先后指针就可以找到这个节点了。
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return head; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode first = dummy; //because n is always valid, so we don't need to get the length of the linked list and do mod to n ListNode second = dummy; while(first.next != null){ first = first.next; n--; if(n < 0) second = second.next; } second.next = second.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) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode fast = dummy, slow = dummy; while (fast.next != null) { fast = fast.next; if (n <= 0) { slow = slow.next; } n--; } slow.next = slow.next.next; return dummy.next; } }
Python:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head slow = dummy fast = dummy while fast.next != None: fast = fast.next if n <= 0: slow = slow.next n -= 1 slow.next = slow.next.next return dummy.next
三刷:
用个例子就很容易能算出来是哪个节点了。 List = {1, 2, 3}, n = 2
Java:
/** * 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 dummy = new ListNode(-1); dummy.next = head; ListNode slow = dummy, fast = dummy; while (fast.next != null) { fast = fast.next; if (n <= 0) { slow = slow.next; } n--; } slow.next = slow.next.next; return dummy.next; } }
Reference:
https://leetcode.com/discuss/37149/3-short-python-solutions