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...
public ListNode removeNthFromEnd(ListNode head, int n) { // nth指向p前n个结点,pre为nth前一个结点,即pre/nth/p ListNode p = head, nth = head, pre = null; while (--n > 0) { p = p.next; } while (p.next != null) { p = p.next; pre = nth; nth = nth.next; } // 此...
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...
}// 删除第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...
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;}//找到被删除结点的前一个结...
19. Remove Nth Node From End of List 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. ...
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;}//找到被删除结点的前一个结...
19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 23. Merge k Sorted Lists 26. Remove Duplicates from Sorted Array 27. Remove Element 28. Implement strStr() 29. Divide Two Integer 30. Substring with Concatenation of All Words ...
def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ my_head = my_trail = head for i in range(n): my_head = my_head.nextif not my_head: return head.nextwhile my_head.next: ...