leetcode - Remove Nth Node From End of List

來源:互聯網
上載者:User

標籤:style   blog   http   color   strong   os   

題目: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.

Note:
Given n will always be valid.
Try to do this in one pass.

 

個人思路:

1、設定兩個指標,一個快,一個慢,根據給定的n,讓快指標先走n步,之後再同時走,直到快指標走到末節點,此時慢指標走到要刪除節點的父節點

2、注意一下邊界條件即可,鏈表為空白、刪除前端節點等情況

代碼:

 1 #include <stddef.h> 2  3 struct ListNode 4 { 5     int val; 6     ListNode *next; 7     ListNode(int x) : val(x), next(NULL) {}; 8 }; 9 10 class Solution11 {12 public:13     ListNode* removeNthFromEnd(ListNode *head, int n)14     {15         if (!head)16         {17             return NULL;18         }19 20         ListNode *slow = head;21         ListNode *fast = head;22 23         //快指標先走n步24         for (int i = 0; i < n; ++i)25         {26             fast = fast->next;27         }28         //快指標為空白,表明要刪除的節點為前端節點29         if (!fast)30         {31             head = head->next;32             delete slow;33             slow = NULL;34 35             return head;36         }37         //快指標走到最後一個節點時,慢指標走到要刪除節點的前一個節點38         while (fast->next)39         {40             slow = slow->next;41             fast = fast->next;42         }43         //刪除節點44         ListNode *deleted = slow->next;45         slow->next = deleted->next;46         delete deleted;47         deleted = NULL;48 49         return head;50     }51 };52 53 int main()54 {55     return 0;56 }
View Code

 

網上的文章大部分都是這個思路

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.