链表节点
ListNode.h
1 #include "stdafx.h" 2 #include<iostream> 3 using namespace std; 4 template <typename Type> class LinkStack; 5 template <typename Type> 6 // 链表节点 7 class ListNode{ 8 private: 9 friend class LinkStack<Type>; 10 ListNode():p_next(NULL){} 11 ListNode(Type item , ListNode<Type>*next=NULL):data(item),p_next(next){} 12 ~ListNode(){ 13 p_next=NULL; 14 } 15 private: 16 Type data; // 节点数据 17 ListNode<Type>*p_next; //下一个节点 18 };
栈节点
LinkNode.h
1 #include "ListNode.h" 2 template <typename Type> 3 class LinkStack{ 4 public: 5 LinkStack():p_top(NULL){} 6 ~LinkStack(){ 7 makeEmpty(); 8 } 9 public: 10 void makeEmpty(); // 清空 11 bool push(Type item); // 入栈 12 Type pop(); // 出栈 13 Type getTop(); // 获取栈首元素 14 void print(); // 打印 15 bool isEmpty(){ // 判空 16 return p_top==NULL; 17 } 18 private: 19 ListNode<Type>*p_top; 20 }; 21 template<typename Type> 22 void LinkStack<Type>::makeEmpty(){ 23 ListNode<Type>*pdel; 24 while(p_top!=NULL){ 25 pdel = p_top; 26 p_top = p_top->p_next; 27 delete pdel; 28 } 29 } 30 template <typename Type> 31 bool LinkStack<Type>::push(Type item){ 32 ListNode<Type>*temp = new ListNode<Type>(item); 33 if(temp==NULL){ 34 cout << "filed push item:"<<item<<endl; 35 return false; 36 } 37 temp->p_next = p_top; 38 p_top = temp; 39 return true; 40 } 41 template <typename Type> 42 Type LinkStack<Type>::pop(){ 43 if(isEmpty()){ 44 cout << "stack is empty , can‘t pop the element"<<endl; 45 exit(0); 46 } 47 ListNode<Type>*temp = p_top; 48 p_top = p_top->p_next; 49 Type item = temp->data; 50 delete temp; 51 return item; 52 } 53 54 template <typename Type> 55 Type LinkStack<Type>::getTop(){ 56 if(isEmpty()){ 57 cout << "stack is empty"<<endl; 58 exit(0); 59 } 60 return p_top->data; 61 } 62 template <typename Type> 63 void LinkStack<Type>::print(){ 64 if(isEmpty()){ 65 cout << "stack is empty"<<endl; 66 exit(0); 67 } 68 ListNode<Type>*pmove = p_top; 69 cout << "stack"; 70 while(pmove!=NULL){ 71 cout << "->" << pmove->data; 72 pmove = pmove->p_next; 73 } 74 cout << endl << endl; 75 }
时间: 2024-10-09 20:51:56