首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >固体排序阵列- LIFO / FIFO

固体排序阵列- LIFO / FIFO
EN

Ethereum用户
提问于 2018-07-17 01:47:53
回答 1查看 1.1K关注 0票数 1

我将通过push()添加到bytes32[]数组中。

当我使用for (uint = 0;i< array.length;i++)遍历数组时,这是先入先出(FIFO)序列,对吗?

怎样才能执行最后的先入先出(LIFO)?

EN

回答 1

Ethereum用户

发布于 2018-07-17 02:47:30

在Solidity的默认数据结构中,它不是默认的,但是您可以轻松地创建一个链接列表并实现LIFO算法。

示例:

代码语言:javascript
复制
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;
    }

}
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/54498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档