[LC] 19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

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.

Follow up:

Could you do this in one pass?

 1 # Definition for singly-linked list.

2 # class ListNode(object):
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution(object):
8 def removeNthFromEnd(self, head, n):
9 """
10 :type head: ListNode
11 :type n: int
12 :rtype: ListNode
13 """
14 dummy = ListNode(-1)
15 dummy.next = head
16 cur, slow = dummy, dummy
17 while n > 0:
18 cur = cur.next
19 n -= 1
20 while cur.next is not None:
21 slow = slow.next
22 cur = cur.next
23 slow.next = slow.next.next
24 return dummy.next
25

 1 # Definition for singly-linked list.

2 # class ListNode(object):
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution(object):
8 def removeNthFromEnd(self, head, n):
9 """
10 :type head: ListNode
11 :type n: int
12 :rtype: ListNode
13 """
14 dummy = ListNode(-1)
15 dummy.next = head
16 cur, slow = dummy, dummy
17 while n > 0:
18 cur = cur.next
19 n -= 1
20 while cur.next is not None:
21 slow = slow.next
22 cur = cur.next
23 slow.next = slow.next.next
24 return dummy.next
25

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3984 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.