C++赋值、复制 链表栈(有图详解)

什么是浅拷贝?

            共同空间:(如图所示)

深拷贝:(如图所示)

代码示例

  1 #include<iostream>
  2 using namespace std;
  3
  4 struct node
  5 {
  6         int data;
  7         node* next;
  8 };
  9
 10 class Stack
 11 {
 12 public:
 13         Stack();//无参构造
 14         bool IsEmpty();//判断栈是否为空
 15         bool push(int);//进栈
 16         bool pop(int&);//出栈
 17         void list(node*);//递归遍历
 18         Stack(Stack&);//拷贝
 19         node* task()//定义借口 获取top
 20         {
 21                 return top;
 22         }
 23 public:
 24         node* top;
 25         int ilen;
 26
 27 };
 28 //递归遍历
 29 void Stack::list(node* top)
 30 {
 31         if(top==NULL)
 32                 return;
 33         list(top->next);
 34         push(top->data);
 35 }
 36 //深拷贝
 37 Stack::Stack(Stack& s)
 38 {
 39         ilen=0;
 40         top=NULL;
 41         list(s.top);
 42 }
 43 //初始化(无参构造)
 44 Stack::Stack():ilen(0)
 45 {
 46         top=NULL;
 47 }
 48 //为空?
 49 bool Stack::IsEmpty()
 50 {
 51         if(top==NULL)
 52                 return true;
 53         else
 54                 return false;
 55 }
 56 //进栈
 57 bool Stack::push(int data)
 58 {
 59         node* pnew=new node;
 60         if(pnew==NULL)
 61                 return false;
 62         pnew->data=data;
 63         pnew->next=top;
 64         top=pnew;
 65         ilen++;
 66         return true;
 67 }
 68 //出栈
 69 bool Stack::pop(int& data)
 70 {
 71         if(IsEmpty()==true)
 72                 return false;
 73         data=top->data;
 74         node* temp=new node;
 75         temp=top;
 76         top=top->next;
 77         delete temp;
 78         ilen--;
 79 }
 80
 81 int main()
 82 {
 83         Stack s;
 84         s.push(1);
 85         s.push(2);
 86         s.push(3);
 87         int value;
 88         Stack s1(s);
 89
 90         while(s1.pop(value))
 91                 cout<<value<<endl;
 92
 93         while(s.pop(value))
 94                 cout<<value<<endl;
 95         cout<<s1.ilen<<endl;
 96 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浅风叶落

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值