[程序代码]
#include<stdio.h>
#include<stdlib.h>
short InitHeadNode(struct Node* &, struct Node* &);
short RearInsert(struct Node* &, struct Node* &, short);
short GetListLength(struct Node* &);
void DeleteNode(struct Node* &, short, short);
void Traversal(struct Node* &);
/* 链表结点定义 */
struct Node
{
short data;
struct Node *next;
};
int main()
{
struct Node *head1;
struct Node *rear1;
/* 初始化头结点 */
if(InitHeadNode(head1, rear1) == -1)
{
/* 头结点申请失败, 程序直接结束 */
exit(0);
}
short temp;
/* 向链表中插入数据结点 */
while(1)
{
while(scanf("%hd", &temp) != 1)
{
while(getchar() != '\n') ;
printf("请输入合法数据.\n");
}
if(temp == -1)
{
break;
}
if(RearInsert(head1, rear1, temp) == -1)
{
/* 申请结点失败 */
exit(0);
}
}
/* 删除链表中比3大且比9小的元素结点 */
DeleteNode(head1, 3, 9);
Traversal(head1);
/* */
return 0;
}
/* 遍历单链表并输出 */
void Traversal(struct Node* &head)
{
struct Node *p = head -> next;
while(p != NULL)
{
printf("%3hd", p -> data);
p = p -> next;
}
putchar('\n');
}
/* 获取表长 */
short GetListLength(struct Node* &head)
{
struct Node *p = head -> next;
short length = 0;
while(p != NULL)
{
length ++;
p = p -> next;
}
return length;
}
/* 尾插法 */
short RearInsert(struct Node* &head, struct Node* &rear, short value)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
if(p != NULL)
{
/* 结点申请成功 */
rear -> next = p;
p -> next = NULL;
p -> data = value;
rear = p;
return 1;
}
else
{
/* 结点申请失败 */
return -1;
}
}
/* 删除单链表中数据域 > mink 且 < maxk 的所有元素结点 */
void DeleteNode(struct Node* &head, short mink, short maxk)
{
struct Node *p = head -> next;
struct Node *q = head;
while(p != NULL)
{
if(p -> data > mink && p -> data < maxk)
{
/* 删除p所指结点 */
q -> next = p -> next;
free(p);
p = q -> next;
}
else
{
p = p -> next;
q = q -> next;
}
}
}
/* 初始化头结点 */
short InitHeadNode(struct Node* &head, struct Node* &rear)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
if(p != NULL)
{
/* 头结点申请成功 */
head = p;
head -> data = 0;
head -> next = NULL;
rear = head;
return 1;
}
else
{
/* 头结点申请失败 */
return -1;
}
}
[运行结果]