在O(1)時間刪除鏈表節點


思路:

時間複雜度要求爲O(1),已知要刪除的節點,可以找到該節點的下一個節點,把下一個節點的相關信息複製到要刪除的節點上,刪除下一個節點,可以達到題目要求。

注意:刪除尾節點時需要遍歷一遍,刪除頭結點時,需要把頭結點移到下一個節點。

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

struct Listnode
{
	int _value;
	Listnode* _next;
};
void Init(Listnode*& head)
{
	Listnode* cur =head;
	if(cur==NULL)
	{
		cur=(Listnode*)malloc(sizeof(Listnode));
		cur->_next=NULL;
		cur->_value=0;
	}
	head=cur;
}

void push(Listnode*& head,int value)
{
	Listnode* cur =head;

		while(cur->_next)
		{
			cur=cur->_next;
		}
		Listnode* tmp=NULL;
		tmp=(Listnode*)malloc(sizeof(Listnode));
		tmp->_next=NULL;
		tmp->_value=value;
		cur->_next=tmp;
	
		

}
void pop(Listnode* head)
{
	Listnode* cur=head;
	Listnode* prev=NULL;
	while(cur->_next!=NULL)
	{
		prev=cur;
		cur=cur->_next;
	}
	prev->_next=NULL;
	free(cur);
	cur=NULL;
}
void print(Listnode* head)
{
	Listnode* cur=head;
	while(cur)
	{
		printf("%d\n",cur->_value);
		cur=cur->_next;
	}
}
Listnode* Find(Listnode* head,int value)
{
	assert(head);
	Listnode* cur=head;
    while(cur)
	{
		if(cur->_value==value)
		{
			return cur;
		}
		else
		{
			cur=cur->_next;
		}
	}
}
void DeleteNode(Listnode* &head,Listnode* pToBeDeleted)
{
	Listnode* cur=head;
	if(cur==NULL)
	{
		return;
	}
	if(pToBeDeleted==head)
	{
		head=cur->_next;
		free(cur);
		cur=NULL;
		return;
	}
	Listnode* last=pToBeDeleted->_next;
	if(last!=NULL)
	{
		pToBeDeleted->_value=last->_value;
		pToBeDeleted->_next=last->_next;
		free(last);
		last=NULL;
	}
	else    //刪除的是尾節點
	{
		Listnode* prev=NULL;
		while(cur->_next!=NULL)
		{
			prev=cur;
			cur=cur->_next;
		}
		prev->_next=NULL;
		free(cur);
		cur=NULL;
	}
}
void test()
{
	Listnode* head=NULL;
	Init(head);
    push(head,1);
	push(head,2);
	push(head,3);
	/*pop(head);*/
	print(head);
	Listnode* tmp=Find(head,1);
	DeleteNode(head,head);
	print(head);

}
int main()
{
	test();
	system("pause");
	return 0;
}

結果:

wKioL1cvLKKiYkkGAAAWpJxGTE8537.png

wKiom1cvK8eC3aMXAAAbSjYwXrU914.png



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章