|
554 | 554 | - LIFO: Last-In First-Out
|
555 | 555 | - It could be implemented with an array:
|
556 | 556 | - We should keep track of the latestest element pushed index which is different from its capacity `len(array)`
|
557 |
| - Push(key): |
| 557 | + - Push(key): |
558 | 558 | if max-index + 1 < len(array):
|
559 | 559 | max-index += 1
|
560 | 560 | array[max-index] = key
|
561 |
| - Top(): |
| 561 | + - Top(): |
562 | 562 | if max-index >= 0:
|
563 | 563 | return array[max-index]
|
564 |
| - Pop(): |
| 564 | + - Pop(): |
565 | 565 | if max-index >= 0:
|
566 | 566 | value = array[max-index]
|
567 | 567 | max-index -= 1
|
568 | 568 | return value
|
569 |
| - Empty(): |
| 569 | + - Empty(): |
570 | 570 | return max-index == -1
|
571 | 571 | - It could be implemented with a Singly-Linked-List:
|
572 |
| - Push(key): list.PushFront(Key) |
573 |
| - Top(): return list.TopFront() |
574 |
| - Pop(): return list.PopFront() |
575 |
| - Empty(): return list.Empty() |
| 572 | + - Push(key): list.PushFront(Key) |
| 573 | + - Top(): return list.TopFront() |
| 574 | + - Pop(): return list.PopFront() |
| 575 | + - Empty(): return list.Empty() |
576 | 576 | - Time Complexity: Array Imp. Singly-Linked List Comment
|
577 | 577 | Push(key): Θ(1) Θ(1)
|
578 | 578 | Key Top(): Θ(1) Θ(1)
|
|
601 | 601 | - We should keep track of the latestest inserted element index (we'll use it for reads): `read-index`
|
602 | 602 | - We should keep track of the most recent inserted element index(we'll use it for writes): `write-index`
|
603 | 603 | - Initially: `read-index == write-index == 0`
|
604 |
| - Empty(): return (read-index == write-index) |
605 |
| - Full(): return (read-index == write-index + 1) |
606 |
| - Enqueue(key): |
| 604 | + - Empty(): return (read-index == write-index) |
| 605 | + - Full(): return (read-index == write-index + 1) |
| 606 | + - Enqueue(key): |
607 | 607 | if Not Full():
|
608 | 608 | array[write-index] = key
|
609 | 609 | write-index = write-index + 1 if write-index < len(array) - 1 else 0
|
610 |
| - Dequeue(): |
| 610 | + - Dequeue(): |
611 | 611 | if Not Empty():
|
612 | 612 | value = array[read-index]
|
613 | 613 | read-index = read-index + 1 if read-index < len(array) - 1 else 0
|
614 | 614 | return value
|
615 | 615 | - It could be implemented with a Doubly-Linked-List with a tail:
|
616 | 616 | - The list head will be used for reads
|
617 | 617 | - The list writes will be used for writes
|
618 |
| - Empty(): return list.Empty() |
619 |
| - Enqueue(key): list.PushBack(Key) |
620 |
| - Dequeue(): list.PopFront() |
| 618 | + - Empty(): return list.Empty() |
| 619 | + - Enqueue(key): list.PushBack(Key) |
| 620 | + - Dequeue(): list.PopFront() |
621 | 621 | - Time Complexity: Array Imp. Singly-Linked List Comment
|
622 | 622 | Push(key): Θ(1) Θ(1)
|
623 | 623 | Key Top(): Θ(1) Θ(1)
|
|
0 commit comments