重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
237. Delete Node in a Linked List
創新互聯長期為近千家客戶提供的網站建設服務,團隊從業經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態環境。為靜安企業提供專業的網站建設、成都做網站,靜安網站改版等技術服務。擁有10多年豐富建站經驗和眾多成功案例,為您定制開發。
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
, the linked list should become 1 -> 2 -> 4
after calling your function.
題目大意:
給定單鏈表中的一個節點,刪除這個節點。
思路:
由于不能知道這個節點的前一節點,所以可以采用將當前要刪除的節點的信息與這一節點的下一節點的信息交換。然后刪除下一個節點。這樣就實現了刪除這個節點。
代碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { if(NULL == node) return ; ListNode * next = node->next; node->val = next->val; node->next = next->next; delete next; } };
題目不是很好懂。
2016-08-12 21:05:17