1. Title Description
- Design an algorithm deleting the incremented value is greater than the ordered list mink and all elements of less than maxk (maxk mink and are given two parameters, which values can be the same elements in the table may be different).
2. Topic analysis
- Respectively, find the first value> the first node and a value mink ≥maxk node, then the pointer modify, delete values greater than and less than maxk mink all elements.
void Delete(LinkList &L, int mink, int maxk)
{
LNode *p, *pre, *q;
p = L->next; // 首元结点
while (p && p->data <= mink)
{
pre = p;
p = p->next; // 查找第一个值>mink的结点
}
if (p)
{
while (p && p->data < maxk)
p = p->next; // 查找第一个值 ≥maxk的结点
q = pre->next; // 修改指针
pre->next = p; // 连接链表未被删除的部分
while (q != p)
{
LNode *s;
s = q->next;
delete q;
q = s; // 释放结点空间
}
}
}
3. code implementation
- main.cpp
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode, *LinkList;
int InitList(LinkList &L)
{
L = new LNode;
L->next = NULL;
return 1;
}
void TraveList(LinkList L)
{
LNode *p;
p = L->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 尾插法建立链表
void CreateList(LinkList &L, int n)
{
L = new LNode;
L->next = NULL;
LNode *r;
r = L;
for (int i = 0; i < n; i++)
{
printf("请输入链表第%d个元素的值:", i + 1);
LNode *s;
s = new LNode;
scanf("%d", &s->data);
s->next = NULL;
r->next = s;
r = s;
}
}
void Delete(LinkList &L, int mink, int maxk)
{
LNode *p, *pre, *q;
p = L->next; // 首元结点
while (p && p->data <= mink)
{
pre = p;
p = p->next; // 查找第一个值>mink的结点
}
if (p)
{
while (p && p->data < maxk)
p = p->next; // 查找第一个值 ≥maxk的结点
q = pre->next; // 修改指针
pre->next = p; // 连接链表未被删除的部分
while (q != p)
{
LNode *s;
s = q->next;
delete q;
q = s; // 释放结点空间
}
}
}
int main()
{
LinkList L1;
if (InitList(L1))
{
printf("L1初始化成功!\n");
}
else
{
printf("L1初始化失败!\n");
}
printf("请输入L1的长度:");
int n1;
scanf("%d", &n1);
CreateList(L1, n1);
TraveList(L1);
int a = 1, b = 5;
printf("删除链表中大于%d小于%d的节点:\n", a, b);
Delete(L1, a, b);
TraveList(L1);
system("pause");
return 0;
}
- operation result