C++鏈棧基本操作

來源:互聯網
上載者:User

標籤:

 1 #include <iostream> 2 using namespace std; 3  4 struct Node 5 { 6     int data; 7     Node *next; 8 }; 9 10 /*初始化鏈棧*/11 void InitChainStack(Node *top)12 {13     top->next=0;14 }15 16 /*往棧裡壓進資料elem*/17 int Push(Node *top, int elem)18 {19     Node *p=(Node*)malloc(sizeof(Node));20     if(p==0)21         return false;22     p->data=elem;23     p->next = top->next;24     top->next=p;25     return true;26 }27 28 /*出棧,並用x返回出棧值*/29 int Pop(Node *top, int &x)30 {31     Node *temp = top->next;    32     if(temp==0)33         return false;34     top->next = temp->next;35     x=temp->data;36     free(temp);37     return true;38 }39 40 /*返回棧頂資料*/41 int GetTop(Node * top, int &x)42 {43     if(top->next==0)44         return false;45     x=top->next->data;46     return true;47 }48 49 /*判斷棧是否為空白*/50 int IsEmpty(Node * top)51 {52     if(top->next==0)53         return true;54     return false;55 }56 57 /*列印棧所有資料元素*/58 void PrintStack(Node *top)59 {60     Node *temp = top->next;61     while(temp!=0)62     {63         cout << temp->data << " ";64         temp=temp->next;65     }66     cout << endl;67 }68 69 void main()70 {71     Node *node=new Node;72     InitChainStack(node);73     74     for(int i=0;i<10;i++)75         Push(node,i);76     int x=0;77     Pop(node,x);78     GetTop(node,x);79     cout << x << endl;80     cout << IsEmpty(node) << endl;81     PrintStack(node);82 }

 

C++鏈棧基本操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.