Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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.
My node:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
start=head
count=1
while start.next!=None:
count+=1
start=start.next
allitem=count
if n==1:
if allitem==1:
return None
else:
start=head
while start.next!=None:
pre_record=start
start=start.next
pre_record.next=None
return head
n=count-n
count=0
start=head
pre_record=start
while start.next!=None:
if count==n:
if pre_record==head and count==0:#Only happen when we remove the head
head=head.next
else:
pre_record.next=start.next
pre_record=start
start=start.next
count+=1
return head
Solution:
https://leetcode.com/playground/new/empty