AcWing 829. 模拟队列
原题链接
简单
作者:
NCpaste
,
2023-05-25 11:44:43
,
所有人可见
,
阅读 23
思路
- 带头结点的单链表
- HEAD指向队头,即push在队尾,pop在队头
注意
- 操作头结点的时候,要新建一个指针,初始的指针不能动,不然后面就乱套了
- 赋值temp的时候,要先在NULL的位置new一下,然后再更改,因为NULL的时候赋值没有指针关联关系,相当于赋值成了野指针
// Right
head->next = new();
temp = head->next;
// Wrong
temp = head->next;
temp = new();
Debug
- 注意pop和push的位置不一样,但一定有一个会while循环到结尾
代码
#include <iostream>
#include <cstring>
using namespace std;
typedef struct link
{
link * next;
int x;
}*LINK;
string s;
int t;
int main ()
{
int n = 0;
LINK head = new link;
head->next = NULL;
cin >> n;
while (n > 0)
{
n --;
cin >> s;
if (s == "push")
{
cin >> t;
LINK temp = head;
while (temp->next)
{
temp = temp->next;
}
temp->next = new link;
temp = temp->next;
temp->x = t;
temp->next = NULL;
}
else if (s == "pop")
{
LINK temp = head->next;
head->next = temp->next;
delete(temp);
}
else if (s == "empty")
{
if (head->next == NULL)
{
cout <<"YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
else if (s == "query")
{
cout << head->next->x << endl;
}
}
return 0;
}