什么是浅拷贝?
共同空间:(如图所示)
深拷贝:(如图所示)
代码示例
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 }