1

I'd like to implement a linked list in contract storage

Something link this:

contract A {

  struct LinkedList {
    uint    value;
    LinkedList storage next; // What goes here? Can I reference the storage of the next struct in solidity?
  }
}

2 Answers 2

1

Within your struct you will want to keep track of the next item in the list

struct LinkedList {
    bytes32 next;
    uint value;
}

Then keep track of the lenth + head of the list and store the structs in a mapping with their ID's

uint public length;
bytes32 public head;
mapping (bytes32 => LinkedList) public listObjects;

You can add entries like this:

function addEntry(uint _number) public returns (bool) {
    LinkedList memory object = LinkedList(head,_number);
    bytes32 id = sha3(_number, length, block.timestamp);
    listObjects[id] = object;
    head = id;
    length++; 
}
0

You do not need a linked list because arrays in Solidity are automatically expanded and this would just add gas execution overhead.

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.