Permalink
Cannot retrieve contributors at this time
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?
LeetCode/remove-nth-node-from-end-of-list
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
60 lines (51 sloc)
1.47 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |