发布网友 发布时间:2022-04-25 16:34
共1个回答
热心网友 时间:2023-10-18 11:56
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
}LinkList;
LNode *ptr;
void CreateHeadNode(LNode *&h)
{
h = (LNode*)malloc(sizeof(LNode));
h->next = NULL;
ptr = h;
}
void Destory(LNode *&h)
{
LNode*p = NULL;
while(h->next)
{
p = h;
h = h->next;
free(p);
}
}
void Insert(int value)
{
LNode *node;
node = (LNode*)malloc(sizeof(LNode));
node->data = value;
node->next = NULL;
ptr->next = node;
ptr = node;
}
void DeleteNode(LNode *&head, int data)
{
LNode *curr = head->next;//当前节点
LNode *pre = head;//当前节点的前驱节点
//找到删除位置
while (curr != NULL && curr->data < data)
{
pre = curr;
curr = curr->next;
}
//删除节点,可能有连续多个需要删除
while (curr != NULL && curr->data == data)
{
LNode*del = curr;
pre->next = curr->next;
curr = curr->next;
free(del);
}
}
void DispList(LinkList *L )
{
LinkList *p = L->next;
while(p != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
int main()
{
int data;
LinkList *list;
int arr[] = {0, 1, 3, 3, 3 ,4, 5, 6, 7, 8};
CreateHeadNode(list);
for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
{
Insert(arr[i]);
}
cout<<"删除前:";
DispList(list);
cout<<"输入待删除的节点值:";
cin>>data;
DeleteNode(list, data);
cout<<"删除后:";
DispList(list);
Destory(list);
return 0;
}
vs2005测试通过:
删除前:0 1 3 3 3 4 5 6 7 8 8 9
输入待删除的节点值:3
删除后:0 1 4 5 6 7 8 8 9
Press any key to continue . . .
删除前:0 1 3 3 3 4 5 6 7 8 8 9
输入待删除的节点值:5
删除后:0 1 3 3 3 4 6 7 8 8 9
Press any key to continue . . .
删除前:0 1 3 3 3 4 5 6 7 8 8 9
输入待删除的节点值:9
删除后:0 1 3 3 3 4 5 6 7 8 8
Press any key to continue . . .