Javascript stack and queue

Source: Internet
Author: User

The Javascript array is a forward-to-day existence. To ecma262v5, it is already a combination of stacks, queues, and iterators. Sometimes we don't need such a powerful thing. Considering that the for loop is too troublesome, we only need a very simple traversal, so we want to simulate one with a common object.

The first is the stack.

 
Function stack () {} stack. prototype = {Add: function (El, pt) {This. _ first = Pt = {// _ first is constantly changing _ next: This. _ first, El: El} If (pt. _ next) {pt. _ next. _ Prev = pt;} return this;} var S = new stack; S. add ("1 "). add ("2 "). add ("3") var Pt = S. _ first; while (PT) {alert (pt. el) Pt = pt. _ next ;}

The next step is queuing, first-in-first-out:

 function Queue () {} queue. prototype = {Add: function (EL) {If (this. _ last) {This. _ last = This. _ last. _ next = {// _ last is the constantly changing El: El, _ next: NULL // sets the _ last attribute to represent the last element, and make the new element a property value} else {This. _ last = This. _ first = {// we need to set a _ first attribute to indicate the first element El: El, _ next: NULL} return this ;}} var q = new queue Q. add ("1 "). add ("2 "). add ("3") var Pt = Q. _ first; while (PT) {console. log (pt. el) Pt = pt. _ next ;}

since each node of the two structures is an object, it can continue to loop, and the direct _ next is null. This avoids the trouble of interruption of false values in a set such as [1, 0, null, 2.

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.