5659 静态链表

TZOJ 5659 静态链表

静态链表,也是线性存储结构的一种,它兼顾了顺序表和链表的优点。

静态链表将数据全部存储在数组中,但存储位置并不连续,查找下一个元素通过一个整型变量(称为"游标",和指针功能类似)完成。

通常,静态链表会维持两个链表:数据链表(存储数据)和备用链表(空闲内存),数据链表的下标从1开始,备用链表的下标从0开始,而链表的末尾游标值为0(0位置不存储数据),例如使用静态链表存储 {1,2,3} 的过程如下:
在这里插入图片描述
静态链表的一个元素类型如下:

typedef struct

{

    int data;//数据

    int cur;//游标

}Node;

创建一个静态链表(带头结点),并对其进行若干的插入和删除操作,输出每次的执行情况。

要求:

当插入一个元素时,取备用链表的第一个元素(非头结点),将其加入到数据列表中。当删除一个元素时,将结点重新放回备用链表的第一个结点位置。
部分代码已经给定,请将其补充完整,提交时请勿包含给定代码。

//创建备用链表
void Reserve(Node a[])
{
    int i;
    for (i=0; i<maxSize; i++)
    {
        a[i].cur=i+1;//将每个数组分量链接到一起
    }
    a[maxSize-1].cur=0;//链表最后一个结点的游标值为0
}

void Print(Node a[], int first)
{
    int t = a[first].cur;
    while (t)
    {
        printf("%d, %d\n",a[t].data,a[t].cur);
        t = a[t].cur;
    }
}

int main()
{
    int head, pos, x;
    char cmd[20];
    Node a[maxSize];
    Reserve(a);
    head = Init(a);//输入数据创建静态链表
    while(scanf("%s", cmd)!=EOF)
    {
        if(strcmp(cmd, "Insert")==0)
        {
            scanf("%d%d", &pos, &x);
            Insert(a, head, pos, x);//将x插入到pos位置前
        }
        else
        {
            scanf("%d", &x);
            Delete(a, head, x);//删除第一个值为x的元素
        }
        Print(a, head);
    }
    return 0;
}

输入:

第一行为n,第二行为n个整数,表示初始情况下链表中的元素值。

随后输入若干命令,命令包含:

(1)插入元素:Insert pos x,表示将x插入到pos位置(从1开始,数据保证位置有效)之前;

(2)删除元素:Delete x,表示删除链表中第一个值为x的元素(不得删除头结点)。

以EOF结束,链表元素最多不会超过10个元素。
输出:

当执行Delete命令时,如果元素不存在,输出Error,单独一行。

每执行完一条指令后,均输出链表各个元素的数据和游标值(逗号+空格隔开),具体格式见样例。

样例输入
2
1 2
Delete 3
Insert 2 3

样例输出
Error
1, 3
2, 0
1, 4
3, 3
2, 0
思路: 用数组模拟指针,插入时通过备用链表头获得用第一个空节点的下标,用第一个空节点存储插入的数据即a[temp],该节点的游标指向插入前该位置的节点,即a[temp].cur = a[t].cur (t 为插入位置的上一个节点)a[t]再指向a[temp].

#include <stdio.h>
#include <string.h>
#define maxSize 13
//创建备用链表
typedef struct {
	int data;
	int cur;
}Node;

int Init(Node a[])
{
	int n, cnt;
	scanf("%d", &n);
	int emp = a[1].cur;
	for (cnt = 1; cnt <= n; cnt++) {
		scanf("%d", &a[emp].data);
		if (cnt != n) {
			a[emp].cur = emp + 1;
			emp++;
		}
		else {
			a[emp].cur = 0;
			emp++;
		}
	}
	a[0].cur = emp;
	return 1;
}
void Insert(Node a[], int head, int pos, int x)
{
	int cnt = 0;
	int t = head;
	while (t) {
		if (cnt == pos - 1) {
			break;
		}
		cnt++;
		t = a[t].cur;
	}
	int temp = a[0].cur;
	a[temp].data = x;
	a[0].cur = a[temp].cur;
	a[temp].cur = a[t].cur;
	a[t].cur = temp;
	
}
void Delete(Node a[], int head, int x)
{
	int t = head;
	int flag = 0;
	while (t) {
		int q = a[t].cur;
		if (a[q].data == x) {
			int tmp_cur = a[0].cur;
			a[0].cur = a[t].cur;
			a[t].cur = a[q].cur;
			a[q].cur = tmp_cur;
			flag = 1;
			break;
		}
		t = a[t].cur;
	}
	if (!flag) {
		printf("Error\n");
	}

}
发布了24 篇原创文章 · 获赞 0 · 访问量 379

猜你喜欢

转载自blog.csdn.net/weixin_43971049/article/details/101976385
今日推荐