我将通过push()添加到bytes32[]数组中。
当我使用for (uint = 0;i< array.length;i++)遍历数组时,这是先入先出(FIFO)序列,对吗?
怎样才能执行最后的先入先出(LIFO)?
发布于 2018-07-17 02:47:30
在Solidity的默认数据结构中,它不是默认的,但是您可以轻松地创建一个链接列表并实现LIFO算法。
示例:
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;
}
}https://ethereum.stackexchange.com/questions/54498
复制相似问题