Skip to content

Instantly share code, notes, and snippets.

@noman-land
Created April 4, 2018 06:49
Show Gist options
  • Save noman-land/44272bbbbd1806cdc32faba8e5614432 to your computer and use it in GitHub Desktop.
Save noman-land/44272bbbbd1806cdc32faba8e5614432 to your computer and use it in GitHub Desktop.
Push and pop to the end
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