#include <stdio.h>
#include <iostream>
using namespace std;
#include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LNodeList;
void InitList_Tear(LNodeList &L) // 尾插法
{
int n = 0;
L = new LNode;
LNodeList r = L;
L->next = NULL;
printf("请输入要插入关键字的个数:");
cin >> n;
for (int i = 1; i <= n; i++)
{
LNodeList s = new LNode;
printf("请输入%d个关键字:", i);
scanf("%d", &s->data);
s->next = nullptr;
r->next = s;
r = s;
}
}
void printfList(LNodeList L) // 打印单链表
{
LNodeList q = L->next;
int i = 0;
while (q != NULL)
{
printf("%d ", q->data);
i++;
q = q->next;
}
printf("单链表长度:%d\n", i);
}
void Delete(LNodeList &L, int mink, int maxk)
{
LNodeList p = L->next;
LNodeList r = L;
LNodeList q;
L->next = nullptr;
while (p)
{
if (p->data <= mink || p->data >= maxk)
{
r->next = p;
r = p;
p = p->next;
}
else
{
q = p;
p = p->next;
free(q);
}
}
r->next = nullptr;
printf("删除区间%d—%d的元素后\n", mink, maxk);
}
int main()
{
LNodeList A;
InitList_Tear(A); // 尾插法
printfList(A);
Delete(A, 4, 8);
printfList(A);
}
运行结果如下