[LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
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 do this in one pass.
移除给定链表的倒数第n个节点,n总是有效的,要求一次遍历完成one pass。
解法1: two pass,先求出链表的总长度,然后在删除node
解法2:双指针,经典题。主要是在一个遍历中找到第n个倒数元素,一个指针先走n步,然后两个指针同步走,直到第一个走到终点,第二个指针指向的就是需要删除的节点。Corner case: head == null; 头节点的处理,比如,1->2->NULL, n =2; 这时,要删除的就是头节点。
Java: Naive Two Pass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null ) return null ; //get length of list ListNode p = head; int len = 0 ; while (p != null ){ len++; p = p.next; } //if remove first node int fromStart = len-n+ 1 ; if (fromStart== 1 ) return head.next; //remove non-first node p = head; int i= 0 ; while (p!= null ){ i++; if (i==fromStart- 1 ){ p.next = p.next.next; } p=p.next; } return head; } |
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null ) return null ; ListNode fast = head; ListNode slow = head; for ( int i= 0 ; i<n; i++){ fast = fast.next; } //if remove the first node if (fast == null ){ head = head.next; return head; } while (fast.next != null ){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return head; } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class ListNode: def __init__( self , x): self .val = x self . next = None def __repr__( self ): if self is None : return "Nil" else : return "{} -> {}" . format ( self .val, repr ( self . next )) class Solution: # @return a ListNode def removeNthFromEnd( self , head, n): dummy = ListNode( - 1 ) dummy. next = head slow, fast = dummy, dummy for i in xrange (n): fast = fast. next while fast. next : slow, fast = slow. next , fast. next slow. next = slow. next . next return dummy. next |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public : ListNode* removeNthFromEnd(ListNode* head, int n) { if (!head->next) return NULL; ListNode *pre = head, *cur = head; for ( int i = 0; i < n; ++i) cur = cur->next; if (!cur) return head->next; while (cur->next) { cur = cur->next; pre = pre->next; } pre->next = pre->next->next; return head; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步