classSolution:defremoveNthFromEnd(self,head,n):# 初始化一个哑节点,它的下一个节点指向链表头节点# 这样做是为了方便处理边界情况,比如删除的是头节点dummy=ListNode(0)dummy.next=head# 初始化快慢指针,初始时都指向哑节点slow=dummyfast=dummy# 快指针先前进n+1步,走到第n+1个节点# 这里加1是为了让快慢...
1ListNode* removeNthFromEnd(ListNode* head,intn) {2ListNode** t1 = &head, *t2 =head;3//t2向后移n个节点4while(n--) t2 = t2->next;5//使t2移到最后一个节点的next,即NULL6//t1指向那个指向待删除节点的指针,即指向待删除节点的上一个节点的next7while(t2 !=NULL) {8t2 = t2->next;9...
}// 删除第n个节点// ListNode nthNode = p1.next;p1.next = p1.next.next;// nthNode.next = null;returndummy.next; } }// Runtime: 6 ms// Your runtime beats 100.00 % of java submissions. Python 实现 # Definition for singly-linked list.# class ListNode:# def __init__(self, x...
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 d...
https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 题目: nth For example, Given linkedlist:1->2->3->4->5,andn=2.After removing the second node from the end,the linkedlistbecomes1->2->3->5. 1. 2. 3. Note: ...
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. 移除链表中倒数第n个节点; 写一个函数来确定要删除的是第几个节点,方法是获取链表总长度len,那么我们要删除的就是第 nth = len - n 个节点...
publicListNoderemoveNthFromEnd(ListNodehead,intn){intlen=0;ListNodeh=head;while(h!=null){h=h.next;len++;}//长度等于 1 ,再删除一个结点就为 null 了if(len==1){returnnull;}intrm_node_index=len-n;//如果删除的是头结点if(rm_node_index==0){returnhead.next;}//找到被删除结点的前一个结...
在LeetCode新手村100题中,题目19M要求删除链表倒数第N个节点,这是一道中等难度的挑战。解决方法主要有两种,即使用快慢指针和优雅的递归法。快慢指针解法是一种直观且不依赖于链表长度的策略,通过维护两个指针,一个快速移动一个节点,另一个保持固定速度,当快指针到达链表尾部时,慢指针正好在倒数第N...
# class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: fast = head slow = head for _ in range(n): fast = fast.next if not fast: return head.next ...
master leetcode-3/removeNthNodeFromEndOfList.go / Jump to Go to file Cannot retrieve contributors at this time 80 lines (59 sloc) 1.41 KB Raw Blame // Source : https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/...