其他分享
首页 > 其他分享> > 剑指offer 删除链表的节点

剑指offer 删除链表的节点

作者:互联网

给定单向链表的头指针和一个节点指针,定义一个函数在O(1)时间内删除该节点。

1 struct ListNode {
2     int val;
3     ListNode *next;
4 };
 1 void DeleteNode(ListNode* &pListHead, ListNode* pToBeDeleted):
 2     if (!pListNode || !pToBeDeleted) {
 3         return;
 4     }
 5 
 6     if (pToBeDeleted->next != nullptr) {//要删除的节点不是尾节点
 7         ListNode* pNode = pToBeDeleted->next;
 8         pToBeDeleted->val = pNode->val;
 9         pToBeDeleted->next = pNode->next;
10         
11         delete pNode;
12         pNode = nullptr;
13     } else if (pListHead == pToBeDeleted) {//链表只有一个节点
14         
15         delete pToBeDeleted;
16         pToBeDeleted = nullptr;
17         pListHead = nullptr;
18     } else {//链表有多个节点,删除尾节点
19         ListNode* pNode = pListHead;
20         while (pNode->next != pToBeDeleted) {
21             pNode = pNode->next;
22         }
23         pNode->next = nullptr;
24         delete pToBeDeleted;
25         pToBeDeleted = nullptr;
26     }
27     

 

标签:ListNode,offer,nullptr,next,链表,pNode,节点,pToBeDeleted
来源: https://www.cnblogs.com/qinduanyinghua/p/11249902.html