题目: 在O(1)的时间内删除链表节点。
给定单向链表的头指针和一个节点指针,定义一个函数在O(1)时间内删除该节点。链表节点与函数的定义如下:struct ListNode { int m_nValue; ListNode *m_pNext; }; void DeleteNode(ListNode ** pListHead, ListNode * pToBeDeleted);
由于是C++解答,必须考虑到释放空间的问题
分情况讨论:
1.只有一个节点,删除节点
2.中间节点,值赋后一节点,指向下下个节点,相当于取代后一节点
3.尾节点,必须找到前序节点才能安全删除
代码:
void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted)
{
if(!pListHead || !pToBeDeleted)
return;
// 要删除的结点不是尾结点
if(pToBeDeleted->m_pNext != nullptr)
{
ListNode* pNext = pToBeDeleted->m_pNext;
pToBeDeleted->m_nValue = pNext->m_nValue;
pToBeDeleted->m_pNext = pNext->m_pNext;
delete pNext;
pNext = nullptr;
}
// 链表只有一个结点,删除头结点(也是尾结点)
else if(*pListHead == pToBeDeleted)
{
delete pToBeDeleted;
pToBeDeleted = nullptr;
*pListHead = nullptr;
}
// 链表中有多个结点,删除尾结点
else
{
ListNode* pNode = *pListHead;
while(pNode->m_pNext != pToBeDeleted)
{
pNode = pNode->m_pNext;
}
pNode->m_pNext = nullptr;
delete pToBeDeleted;
pToBeDeleted = nullptr;
}
}
第一行是删除指针所指的内容
第二行是指针指向空
必须一起使用
delete pToBeDeleted;
pToBeDeleted = nullptr;
题目: 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
每当有重复的记忆前序节点即可。
#include "pch.h"
#include<iostream>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
void DeleteDuplication(ListNode** pHead) {
ListNode* pNode = *pHead;
ListNode* pPreNode = nullptr;
while (pNode != nullptr) {
if (pNode->m_pNext && pNode->m_pNext->m_nValue == pNode->m_nValue) {
while (pNode->m_pNext && pNode->m_pNext->m_nValue == pNode->m_nValue) {
pNode = pNode->m_pNext;
}
if (pPreNode == nullptr){
*pHead = pNode->m_pNext;
}
else {
pPreNode->m_pNext = pNode->m_pNext;
}
}
else
{
pPreNode = pNode;
}
pNode = pNode->m_pNext;
}
}
int main()
{
ListNode* n1 = new ListNode();
n1->m_nValue = 3;
n1->m_pNext = nullptr;
ListNode* n2 = new ListNode();
n2->m_nValue = 2;
n2->m_pNext = n1;
ListNode* n3 = new ListNode();
n3->m_nValue = 1;
n3->m_pNext = n2;
ListNode* n4 = new ListNode();
n4->m_nValue = 3;
n4->m_pNext = n3;
ListNode* n5 = new ListNode();
n5->m_nValue = 3;
n5->m_pNext = n4;
ListNode** pHead = &n5;
DeleteDuplication(pHead);
cout << 1;
}