#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node *head = NULL;
Node* createN(int x) {
Node *newnode;
newnode
= (Node
*)malloc(sizeof(Node
)); newnode->val = x;
newnode->next = NULL;
return newnode;
}
void freeL() {
Node *p;
while (head != NULL) {
p = head->next;
head = p;
}
}
void insHead(int x) {
Node *p = createN(x);
p->next = head;
head = p;
}
void insTail(int x) {
Node *p = head;
if (p == NULL) {
head = createN(x);
return;
}
while (p->next != NULL) {
p = p->next;
}
p->next = createN(x);
}
void delHead() {
if (head == NULL) return; // リストが空の場合は何もしない
Node *p = head;
head = head->next;
}
void delTail() {
if (head == NULL) return; // リストが空の場合
if (head->next == NULL) { // リストが1つだけの場合
head = NULL;
return;
}
Node *p = head;
while (p->next->next != NULL) {
p = p->next;
}
p->next = NULL;
}
void push(int x) {
insHead(x); // スタックの push: 先頭に挿入
}
int pop() {
if (head == NULL) {
return -1; // スタックが空の場合
}
int value = head->val;
delHead();
return value;
}
void enqueue(int x) {
insTail(x); // キューの enqueue: 末尾に挿入
}
int dequeue() {
if (head == NULL) {
return -1; // キューが空の場合
}
int value = head->val;
delHead();
return value;
}
int main(void) {
int s1, s2, s3, q1, q2, q3;
// スタック操作
push(1);
push(2);
push(3);
s1 = pop();
s2 = pop();
s3 = pop();
printf("%d %d %d\n", s1
, s2
, s3
);
// キュー操作
enqueue(1);
enqueue(2);
enqueue(3);
q1 = dequeue();
q2 = dequeue();
q3 = dequeue();
printf("%d %d %d\n", q1
, q2
, q3
);
freeL();
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCnR5cGVkZWYgc3RydWN0IG5vZGUgewogICAgaW50IHZhbDsKICAgIHN0cnVjdCBub2RlICpuZXh0Owp9IE5vZGU7CgpOb2RlICpoZWFkID0gTlVMTDsKCk5vZGUqIGNyZWF0ZU4oaW50IHgpIHsKICAgIE5vZGUgKm5ld25vZGU7CiAgICBuZXdub2RlID0g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