Created
April 4, 2018 06:49
-
-
Save noman-land/44272bbbbd1806cdc32faba8e5614432 to your computer and use it in GitHub Desktop.
Push and pop to the end
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.21; | |
contract LinkedList { | |
bool public isEmpty = true; | |
uint public length = 0; | |
bytes32 public head; | |
bytes32 public tail; | |
struct LinkNode { | |
string value; | |
bytes32 next; | |
bytes32 prev; | |
} | |
mapping (bytes32 => LinkNode) public nodes; | |
function push(string value) public { | |
bytes32 key = keccak256(value, length); | |
nodes[key].value = value; | |
if (length++ == 0) { | |
head = key; | |
isEmpty = false; | |
} else { | |
nodes[tail].next = key; | |
nodes[key].prev = tail; | |
} | |
tail = key; | |
} | |
function pop() public returns(string) { | |
require(length > 0); | |
tail = nodes[tail].prev; | |
delete nodes[tail].next; | |
if (--length == 0) { | |
delete nodes[head].next; | |
delete head; | |
isEmpty = true; | |
} | |
return nodes[tail].value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment