當前位置:
首頁 >
LeetCode Algorithm 19. 删除链表的倒数第 N 个结点
發布時間:2024/5/17
34
豆豆
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 19. 删除链表的倒数第 N 个结点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
19. 刪除鏈表的倒數第 N 個結點
Ideas
鏈表經典題目,還是09年考研408數據結構最后一道大題,在LeetCode上只能算中等難度的題目。
說回題目其實不難,之前跟著左神練了很多雙指針的題目,所以一下就能想到。
簡單說一下思路:快慢指針,quick指針先走n步,然后quick指針和slow指針一起往后走,quick指針到達尾結點的時候,quick指針正好到達導數第n個結點。
大體思路是這樣,需要扣一下細節:如果head = [1], n = 1的話,只有一個節點,為了除了這種情況,新建一個pre結點放在head前面,然后讓slow從pre開始走。
Code
C++
class Solution { public:ListNode* removeNthFromEnd(ListNode* head, int n) {ListNode* pre = new ListNode(0, head);ListNode* slow = pre;ListNode* quick = head;for (int i = 0; i < n; i++) {quick = quick->next;}while (quick) {quick = quick->next;slow = slow->next;}slow->next = slow->next->next;return pre->next;} };Python
class Solution:def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:pre = ListNode(0, head)first, second = head, prefor i in range(n):first = first.nextwhile first:first = first.nextsecond = second.nextsecond.next = second.next.nextreturn pre.next總結
以上是生活随笔為你收集整理的LeetCode Algorithm 19. 删除链表的倒数第 N 个结点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Matrix工作室第六届纳新AI组考核题
- 下一篇: 143. Reorder List 重排