classSolution:defremoveNthFromEnd(self,head,n):# 初始化一个哑节点,它的下一个节点指向链表头节点# 这样做是为了方便处理边界情况,比如删除的是头节点dummy=ListNode(0)dummy.next=head# 初始化快慢指针,初始时都指向哑节点slow=dummyfast=dummy# 快指针先前进n+1步,走到第n+1个节点# 这里加1是为了让快慢...
题目: 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...
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; } // 此...
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...
After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Givennwill always be valid. 方法一:双指针 删除倒数第n个点,我们首先得找到倒数第n个点才行。因为链表只能从头开始找,倒数第n个点就是正数第m-n(设链表长是m)。我让第一个指针先走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;}//找到被删除结点的前一个结...
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;}//找到被删除结点的前一个结...
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode top = new ListNode(Integer.MIN_VALUE); top.next = head; ListNode p = top; if(n==1){ while(p.next.next!=null) p = p.next; p.next = null; return top.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 ...