Stack chain implementation

Source: Internet
Author: User

CodeAs follows:

<textarea cols="50" rows="15" name="code" class="cpp">Class cstacklinkimpl; <br/> class cstacknode {<br/> friend class cstacklinkimpl; <br/> PRIVATE: <br/> int data; <br/> cstacknode * link; <br/> Public: <br/> cstacknode (int d, cstacknode * l = NULL): Data (D), Link (l) {}< br/> ~ Cstacknode () {}< br/>}; <br/> class cstacklinkimpl {<br/> Public: <br/> cstacklinkimpl (): Top (null) {}< br/> ~ Cstacklinkimpl (); <br/> bool isempty () {return Top = NULL ;}< br/> int POP (); <br/> int gettop (); <br/> void push (INT value); <br/> PRIVATE: <br/> cstacknode * Top; <br/> };</textarea> <textarea cols="50" rows="15" name="code" class="cpp">Int cstacklinkimpl: Pop () {<br/> assert (! Isempty (); <br/> cstacknode * pnode = top; <br/> // Top = pnode-> link; <br/> // return pnode-> data; <br/> int value = pnode-> data; <br/> Top = pnode-> link; <br/> Delete pnode; <br/> return value; <br/>}< br/> void cstacklinkimpl: Push (INT value) {<br/> cstacknode * pnode = new cstacknode (value, top ); <br/> Top = pnode; <br/>}< br/> int cstacklinkimpl: gettop () {<br/> assert (! Isempty (); <br/> return top-> data; <br/>}< br/> cstacklinkimpl ::~ Cstacklinkimpl () {</P> <p> cstacknode * pnode; <br/> while (top! = NULL) {<br/> pnode = top; <br/> Top => link; <br/> Delete pnode; <br/>}< br/>}</textarea>

 

In this process, I learned the following:

1. usage of the friend class. To allow Class A to have higher access permissions to Class B, it is necessary to point out in the declaration or definition of Class B that Class A is its friend class.

2. Top is the stack top, and push and pop change is the top. This is the stack idea.

3. Pay attention to releasing resources during pop. (The commented-out code is problematic)

4. Implementation of one-way linked list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.