#include "List.h"
#include <stack>
using namespace std;
//使用栈,时间复杂度N,空间复杂度N
Node* removeN1(Node* head, int num)
{
stack<Node*> nStack;
while(head)
{
if(head->value != num)
nStack.push(head);
head = head->next;
}
while(!nStack.empty())
{
Node* cur = nStack.top();
cur->next = head;
head = cur;
nStack.pop();
}
return head;
}
Node* removeN2(Node* head, int num)
{
while(head)
{
if(head->value != num)
break;
head = head->next;
}
Node* pre = head;
Node* cur = head;
while(cur)
{
if(cur->value == num)
pre->next = cur->next;
else
pre = cur;
cur = cur->next;
}
return head;
}
int main()
{
Node* pNode0 = new Node(0);
Node* pNode1 = new Node(1, pNode0);
Node* pNode2 = new Node(2, pNode1);
Node* pNode3 = new Node(2, pNode2);
Node* pNode4 = new Node(1, pNode3);
Node* pNode5 = new Node(0, pNode4);
pNode5 = removeN1(pNode5, 1);
Print(pNode5);
cout << "===============" << endl;
pNode5 = removeN2(pNode5, 0);
Print(pNode5);
}
在单链表中删除指定值的节点
猜你喜欢
转载自blog.csdn.net/wzc2608/article/details/80682813
今日推荐
周排行