#include <iostream>
#include <vector>
using namespace std;
struct Node{
int num;
Node * next;
Node(int a){
this->num = a;
this->next = NULL;
}
};
//用数组初始化链表
Node * init(int * nums, int size)
{
Node * root = new Node(0);
//1.头结点很方便。 2.root必须有指向一个对象,如果是NULL,则没没办法赋值
Node * pre = root;
for(int i = 0; i < size; i++){
Node * temp = new Node(nums[i]);
pre->next = temp;
pre = pre->next;
}
return root;
}
void print(Node * root)
{
Node * iterator = root;
while(iterator != NULL){
cout << iterator->num << " ";
iterator = iterator->next;
}
}
class MyStack{
private:
Node * head;
public:
MyStack(){
head = NULL;
}
void push(int n)
{
Node * temp = new Node(n);
if(head != NULL){
temp->next = head;//栈顶在链表的头部
}
head = temp;
}
void pop()
{
if(head == NULL)return ;
head = head->next;
}
int size()
{
int count = 0;
Node * p = head;
while(p != NULL){
count++;
p = p->next;
}
return count;
}
void print()
{
Node * p = head;
while(p != NULL){
cout << p->num << " ";
p = p->next;
}
cout << endl;
}
};
int main()
{
int nums[5] = {1, 2, 3, 4, 5};
MyStack s;
for(int i = 0; i < 5; i++){
s.push(nums[i]);
}
//s.push(1);
s.print();
cout << s.size() << endl;
s.pop();
s.print();
cout << s.size() << endl;
return 0;
}
c++ 关于链表和链表实现栈
最新推荐文章于 2024-07-16 20:03:40 发布