面试题-数组实现栈(动态扩容)

师兄和我说的一道面试题,自己动手写了一下,不难,重点在于动态扩容。(和vector的扩容类似)

typedef struct mystack
{
	int top;
	int*data;
	int size;
}mystack;
void init(mystack*s)
{
	s->top = -1;
	s->data = new int[5];
	s->size = 5;
}
void push(mystack*s, int elem)
{
	if (s->top + 1 < s->size)
	{
		s->top++;
		s->data[s->top] = elem;
		cout << elem << "成功入栈" << endl;
	}
	else
	{
		//需要扩容
		int *new_data = new int[2 * s->size];
		for (int i = 0; i < s->size; i++)
		{
			new_data[i] = s->data[i];
		}
		delete[] s->data;
		s->data = new_data;
		s->size = 2 * s->size;

		s->top++;
		s->data[s->top] = elem;
		cout << elem << "成功入栈" << endl;
	}
}

void pop(mystack*s)
{
	if (s->top != -1)
	{
		cout << s->data[s->top] << "成功出栈" << endl;
		s->top--;
	}
	else
	{
		cout << "栈已经为空" << endl;
	}
}

int main()
{
	mystack s;
	init(&s);
	push(&s, 1);
	push(&s, 2);
	push(&s, 3);
	push(&s, 4);
	push(&s, 5);
	cout << s.size << endl;
	push(&s, 6);
	cout << s.size << endl;
	pop(&s);
	pop(&s);
	pop(&s);
	pop(&s);
	pop(&s);
	pop(&s);
	pop(&s);

	delete[] s.data;
	system("pause");
	return 0;
}

在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页