《程式員面試金典》訪問單個節點的刪除,程式員面試金典

來源:互聯網
上載者:User

《程式員面試金典》訪問單個節點的刪除,程式員面試金典

【 聲明:著作權,轉載請標明出處,請勿用於商業用途。  聯絡信箱:libin493073668@sina.com】


題目連結:http://www.nowcoder.com/practice/75e0235da04141d4823eb74018e9e0bc?rp=1&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking-the-coding-interview/question-ranking


題目描述
實現一個演算法,刪除單向鏈表中間的某個結點,假定你只能訪問該結點。
給定帶刪除的節點,請執行刪除操作,若該節點為尾節點,返回false,否則返回true

思路
要刪除本結點,但是在前一個結點無法找到的情況下,我們怎麼刪除這個結點呢?我們可以轉換一下思路,首先我們可以將下一個結點賦值給本結點,這就相當於刪除了這個結點了,但是此時鏈表中有了重複的結點,我們只需要將此時結點的next指向原本下一個結點的next就完成了刪除的操作


/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};*/class Remove{public:bool removeNode(ListNode* pNode){// write code hereif(pNode==nullptr || pNode->next==nullptr)return false;ListNode *pNext = pNode->next;pNode->val = pNext->val;pNode->next = pNext->next;return true;}};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.