I am adding to an bytes32[] array via push().

When I traverse the array with for (uint i = 0; i < array.length; i++), This is First in First Out (FIFO) sequence right?

How can one perform a Last in First Out (LIFO)?

1 Answer 1


You don't have it as default inside the Solidity's default data structure but you can easily create a linked list and implement the LIFO algorithm.


pragma solidity ^0.4.0;

contract A {
    struct Node { 
        uint256 value;
        bytes32 nextNode;
    bytes32 head;
    mapping(bytes32 => Node) list;

    function push(uint256 value) public {
        bytes32 key = keccak256(abi.encodePacked(value, head));
        Node memory newNode = Node(value, head);

        list[key] = newNode;
        head = key;

    function headValue() public view returns(uint256) {
        require(head != 0);

        return list[head].value;

    function sum() public view returns(uint256) {
        bytes32 current = head;
        uint256 total = 0;
        while (current != 0) {
            total += list[current].value;
            current = list[current].nextNode;

        return total;

  • 3
    Or he can simply do for (uint i = array.length; i > 0; i--), and handle array[i - 1] at every iteration. This dude hasn't mentioned anything about removing an arbitrary item from the array, so a linked-list implementation seems like a huge overkill in this case. Commented Feb 10, 2019 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.