Created
September 9, 2013 00:16
-
-
Save cscorley/6489865 to your computer and use it in GitHub Desktop.
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
from ctypes import * | |
class Cell(Structure): | |
pass | |
Cell._fields_ = [ | |
("val", c_int), | |
("next", POINTER(Cell))] | |
class LinkedList: | |
def __init__(self, iterable=None): | |
if iterable is None: | |
pass | |
else: | |
pass | |
self.length = 0 | |
self._head = None | |
def __len__(self): | |
return self.length | |
def head(self): | |
return self._head | |
def append(self, val): | |
p = self.head() | |
new = Cell(val=val) | |
if p is None: | |
self._head = new | |
else: | |
for i in range(len(self)-1): | |
p = p.next.contents | |
p.next = pointer(new) | |
self.length += 1 | |
def get(self, index): | |
assert index < len(self) | |
assert index >= 0 | |
p = self.head() | |
while index > 0: | |
p = p.next.contents | |
index -= 1 | |
return p.val | |
def __getitem__(self, n): | |
self.get(n) | |
def insert(self, index, val): | |
assert index < len(self) | |
assert index >= 0 | |
index -= 1 | |
p = self.head() | |
while index > 0: | |
p = p.next.contents | |
index -= 1 | |
new = Cell() | |
new.val = val | |
new.next = p.next | |
p.next = pointer(new) | |
self.length += 1 | |
def remove(self, index): | |
assert index < len(self) | |
assert index >= 0 | |
index -= 1 | |
p = self.head() | |
while index > 0: | |
p = p.next.contents | |
index -= 1 | |
p.next = p.next.contents.next | |
self.length -= 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment