【ACM】杭电OJ 2019

可以用链表写,也可以用顺序表写:

下面是链表的AC代码:

#include 
#include 
typedef struct node
{
	int info;
	struct node* next;
}N;
N* init()
{
	return NULL;
}
N* creat(N* head,int n)
{
	int i,x;
	N *p, *q = NULL;
	for (i = 1; i <= n; i++)
	{
		scanf_s("%d", &x);
		p = (N*)malloc(sizeof(N));
		p->info = x;
		p->next = NULL;
		if (!head)
		{
			head = p;
			q = p;
		}
		else
		{
			q->next = p;
			q = p;
		}
	}
	return head;
}
void display(N* head)
{
	N *p=head;
	while (p)
	{
		if (p->next)
			printf("%d ", p->info);
		else
			printf("%d\n",p->info);
		p = p->next;
	}
}
N *insert(N* head,int x)
{
	N *p,*q=head,*qq=head->next;
	p = (N*)malloc(sizeof(N));
	p->info = x;
	if (p->info <= head->info)
	{
		p->next = head;
		head = p;
		return head;
	}
	while (qq)
	{
		if (p->info >= q->info && p->info <= qq->info)
		{
			p->next = qq;
			q->next = p;
			break;
		}
		else
		{
			q = qq;
			qq = qq->next;
		}
	}
	if (!qq)
	{
		q->next = p;
		p->next = NULL;
	}
	return head;
}
int main()
{
	N *h;
	int m, n;
	while (scanf_s("%d%d", &n, &m) != EOF)
	{
		if (n == 0 && m == 0)	return 0;
		h = init();
		h = creat(h, n);
		h = insert(h, m);
		display(h);
	}
	return 0;
}

下面是通过移动数组的元素进行:

#include 
#include 
#include 
int main()
{
	int a[110], n, t, i,  m;
	while (scanf_s("%d%d", &n, &m) != EOF)
	{
		if (m == 0 && n == 0)return 0;
		t = -1;
		memset(a, 0, sizeof(a));
		if (m == 0 && n == 0)	return 0;
		for (i = 0; i < n; i++)
		{
			scanf_s("%d", &a[i]);
			if (a[i] < m)
			{
				t = i;
			}
		}
		if (t == -1)
		{
			for (i = n; i >= 1; i--)
			{
				a[i] = a[i - 1];
			}
			a[0] = m;
		}
		else if(t= t + 1; i--)
			{
				a[i] = a[i - 1];
			}
			a[t + 1] = m;
		}
		else if (t == n - 1)
		{
			a[n] = m;
		}
		for (i = 0; i <= n; i++)
		{
			if (i != n)
			{
				printf("%d ", a[i]);
			}
			else
			{
				printf("%d\n", a[i]);
			}
		}
	}
	return 0;
}

上面的是用数组写的。

你可能感兴趣的:(OJ)