Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class linkst:
- __slots__ = ['data', 'next']
- def __init__(self, iterable=(), data=None, next=None):
- if iterable is not None:
- self.data, self.next = self, None
- self.extend(iterable)
- else:
- self.data, self.next = data, next
- def empty(self):
- return self.next is None
- def append(self, data):
- last = self.data
- self.data = last.next = linkst(None, data)
- def insert(self, data, index=0):
- curr, cat = self, 0
- while cat < index and curr:
- curr, cat = curr.next, cat+1
- if index<0 or not curr:
- raise IndexError(index)
- new = linkst(None, data, curr.next)
- if curr.next is None: self.data = new
- curr.next = new
- def reverse(self):
- current, prev = self.next, None
- while current:
- next = current.next
- current.next = prev
- prev, current = current, next
- if self.next: self.data = self.next
- self.next = prev
- def delete(self, index=0):
- curr, cat = self, 0
- while cat < index and curr.next:
- curr, cat = curr.next, cat+1
- if index<0 or not curr.next:
- raise IndexError(index)
- curr.next = curr.next.next
- if curr.next is None:
- self.data = curr
- def remove(self, data):
- current = self
- while current.next:
- if data == current.next.data: break
- current = current.next
- else: raise ValueError(data)
- current.next = current.next.next
- if current.next is None:
- self.data = current
- def __contains__(self, data):
- current = self.next
- while current:
- if data == current.data:
- return True
- current = current.next
- return False
- def __iter__(self):
- itr = linkst()
- itr.next = self.next
- return itr
- def __next__(self):
- if self.data is not self or self.next is None:
- raise StopIteration()
- next = self.next
- self.next = next.next
- return next.data
- def __repr__(self):
- return 'linkst(%r)'%list(self)
- def __str__(self):
- return '->'.join(str(i) for i in self)
- def extend(self, iterable):
- last = self.data
- for i in iterable:
- last.next = linkst(None, i)
- last = last.next
- self.data = last
- def index(self, data):
- current, idx = self.next, 0
- while current:
- if current.data == data: return idx
- current, idx = current.next, idx+1
- raise ValueError(data)
- a=linkst()
- a.append(6)
- a.append(5)
- a.append(5)
- a.append(12)
- a.append(32)
- print(a)
- a.remove(5)
- print(a)
- for i in a:
- print (i)
- if 6 in a:
- print("123")
Advertisement
Add Comment
Please, Sign In to add comment