剑指offer-面试题13.在O(1)时间删除链表节点

时间:2023-02-15 11:39:08

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

链表节点与函数的定义如下。

通常我们删除某个节点都是从头开始遍历到需要删除节点的前一个节点。

然后使得该节点的next指向删除节点的next即可,这样看来删除一个节点

的复杂度为O(n)然而我们其实遍历的目的只是想获取想要删除节点的前一

个节点。

那么我们可以这样考虑:

我们把要删除节点下一个节点的值赋值到当前节点,然后将当前节点的下一个

节点删除即可。

比如:

一个链表3->2->5->7->9给定的指针指向5也就是说要删除5这个节点。

我们将节点5下个节点的值赋值给需要删除的节点即:

3->2->7->7->9

然后再p->next=p->next->next即可删除

代码实现如下:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node)
{
if(node==NULL)
return; struct ListNode* p,*q;
q=node;
p=node->next;
q->val=p->val;
q->next=p->next; }

勘误:

上面的方法没有考虑到当要删除的结点是尾结点的情况

因此当需要删除的结点为尾结点的时候这时候仍需要

从头遍历到尾结点的前面一个结点。

但是算法复杂度仍然为1,因为只有一个尾结点需要遍历

整个链表,复杂度为(O(n)+O(1)*(n-1))/n=O(1)

代码实现如下:

 #include <iostream>
using namespace std; /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode
{
int val;
struct ListNode *next;
}; ListNode *head; void deleteNode(struct ListNode* node)
{
if(node==NULL)
return;
if(node->next==NULL)
{
ListNode *TempHead;
TempHead=head;
while(TempHead->next->next!=NULL)
{
TempHead=TempHead->next;
}
TempHead->next=NULL;
return;
} struct ListNode *p,*q;
q=node;
p=node->next;
q->val=p->val;
q->next=p->next;
} ListNode* CreateList()
{
ListNode *Head,*p;
Head=(ListNode*)malloc(sizeof(ListNode));
if(Head==NULL)
return NULL; Head->val=;
Head->next=NULL;
p=Head;
while(true)
{
int data;
cout<<"Please input Node data: ";
cin>>data;
if(data==)
{
break;
}
else
{
ListNode* NewNode;
NewNode=(ListNode*)malloc(sizeof(ListNode));
NewNode->val=data;
NewNode->next=NULL;
p->next=NewNode;
p=p->next;
}
} return Head->next;
} void PrintList(ListNode* Head)
{
ListNode *p;
p=Head; while(p!=NULL)
{
cout<<p->val<<",";
p=p->next;
}
} ListNode* GetNodePtr(ListNode* Head)
{
int count;
ListNode* p;
p=Head;
cout<<"Please input the Node Order you want to delete: ";
cin>>count;
int i=;
while(i<count-)
{
p=p->next;
i++;
} return p;
} int main()
{
ListNode *Node;
head=CreateList();
cout<<"The list is: ";
PrintList(head);
cout<<endl;
Node=GetNodePtr(head);
deleteNode(Node);
cout<<"The delete node list is: ";
PrintList(head);
cout<<endl;
return ;
}

测试结果如下:

剑指offer-面试题13.在O(1)时间删除链表节点

感谢@rainhard指出这个错误