# Remove Nth Node From End of List ###### tags: `Medium` `Linked List` >question : https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/603/ ```java= /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head; int length = 0; ListNode first = head; while (first != null) { length++; first = first.next; } length -= n; first = dummy; while (length > 0) { length--; first = first.next; } first.next = first.next.next; return dummy.next; } } ``` - python 分別用兩個指標,fast指向最後,slow指向與fast距離n的位置,即要刪除的節點 ```python= # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ slow = fast = head while n > 0: fast = fast.next n -= 1 if fast == None: head = head.next return head while fast.next != None: slow = slow.next fast = fast.next slow.next = slow.next.next #刪除第n個節點 return head ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up