双向链表
struct node {
int val;
node* next;
node* pre;
};
class stack {
public:
stack() {
head=new node;
head->next = nullptr;
tail = head;
}
~stack() {
while (tail) {
p = tail;
tail = tail->next;
delete p;
}
delete head;
}
void push(int x) {
p = new node;
p->val = x;
tail->next = p;
p->pre = tail;
tail = p;
}
void pop() {
if (isEmpty()) {
cout << "栈为空!" << endl;
return;
}
p = tail;
tail = tail->pre;
p->pre = nullptr;
tail->next = nullptr;
delete p;
}
int top() {
if (isEmpty()) {
cout << "栈为空!" << endl;
return -1;
}
return tail->val;
}
int bottom() {
if (!isEmpty()) {
cout << "栈为空!" << endl;
return -1;
}
return head->next->val;
}
bool isEmpty() {
if (tail == head)
return 1;
return 0;
}
bool ifFull() {
if (isEmpty())
return 0;
return 1;
}
private:
node* tail,*head,*p;
};
单链表
struct node {
int val;
node* next;
};
class stack {
public:
stack() {
head=new node;
head->next = nullptr;
tail = head;
}
void push(int x) {
p = new node;
p->val = x;
p->next=head->next;
head->next=p;
tail = p;
}
void pop() {
if (isEmpty()) {
cout << "栈为空!" << endl;
return;
}
p = tail;
head->next = p->next;
p->next = nullptr;
delete p;
tail = head->next;
}
int top() {
if (isEmpty()) {
cout << "栈为空!" << endl;
return -1;
}
return tail->val;
}
bool isEmpty() {
if (!tail||tail == head)
return 1;
return 0;
}
bool ifFull() {
if (isEmpty())
return 0;
return 1;
}
private:
node* tail,*head,*p;
};