#include<iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct Node* LinkList; //指针类型取别名
LinkList creatList(LinkList head, int n)
{
LinkList p = new Node;
head->next = p;
for(int i = 2; i <= n;i++)
{
LinkList q = new Node;
p ->next = q;
p = q;
}
p->next = NULL;
return head;
}
void initList(LinkList head)
{
LinkList p = head->next;
int i = 1;
for(;p!= NULL;p=p->next)
{
cout<<"请输入第"<<i++<<"个节点的值:" ;
cin>>p->data;
}
}
void printList(LinkList head)
{
LinkList p = head->next;
int i = 1;
for(; p!=NULL; p = p->next)
{
cout<<"第"<<i++<<"个节点的值为:";
cout<<p->data<<endl;
}
}
void deleteNode(LinkList head,int mink,int maxk)
{
LinkList p = head, q = NULL;
while(p ->next != NULL)
{
if(p->next->data >= mink && p->next->data <= maxk) //因为有头结点,所以判断的是next的值
{
q = p->next;
p ->next = q->next;
delete q;
}
else //加else才能保证当节点符合条件时,先删除该节点而不移动指针,这样指针可以判断已删除节点的下一个节点是否符合条件,否则,满足条件的节点删除的同时会指针后移一位,会掠过已删除节点的下一个节点
p = p->next;
}
}
int main()
{
int mink,maxk;
LinkList head = new Node;
head = creatList(head,5);
initList(head);
printList(head);
cout<<"请输入要删除的数据范围最小值:";
cin>>mink;
cout<<"请输入要删除的数据范围最大值:";
cin>>maxk;
//cout<<mink<<maxk<<endl;
deleteNode(head,mink,maxk);
printList(head);
}