Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # LOOK FOR "NEW LINE" (use CTRL+F)
- class Node:
- def __init__(self, val, nxt=None):
- self.val = val
- self.nxt = nxt
- class LinkedList:
- def __init__(self):
- self.head = None
- self.tail = None # NEW LINE
- self.count = 0
- def get_count(self):
- return self.count
- def is_empty(self):
- return (self.get_count() == 0)
- def __str__(self):
- ret = []
- curr = self.head
- while curr != None:
- ret.append(curr.val)
- curr = curr.nxt
- return str(ret)
- def get_node_at(self, idx):
- if idx >= self.get_count() or idx < -self.get_count():
- raise IndexError("list index out of range")
- if idx == -1: # shortcut case # NEW LINE
- return self.tail # NEW LINE
- if idx < 0: # negative index = start counting from the back
- idx = self.get_count()+idx
- curr = self.head
- for i in range(idx):
- curr = curr.nxt
- return curr
- def __getitem__(self, idx):
- return (self.get_node_at(idx)).val
- def insert_front(self, val):
- self.count += 1
- self.head = Node(val, self.head)
- if self.get_count() == 1: # NEW LINE
- self.tail = self.head # NEW LINE
- def insert_back(self, val):
- if self.is_empty():
- self.head = Node(val, None)
- self.tail = self.head # NEW LINE
- self.count += 1
- return
- self.tail.nxt = Node(val, None) # NEW LINE
- self.tail = self.tail.nxt # NEW LINE
- self.count += 1
- def delete_front(self):
- if self.is_empty():
- raise IndexError("deleting from an empty list")
- self.head = self.head.nxt
- self.count -= 1
- if self.is_empty(): # NEW LINE
- self.tail = None # NEW LINE
- def delete_at(self, idx):
- if self.is_empty():
- raise IndexError("deleting from an empty list")
- if idx >= self.get_count() or idx < -self.get_count():
- raise IndexError("list index out of range")
- if idx == 0 or idx == -self.get_count():
- self.delete_front()
- return
- curr = self.get_node_at(idx-1)
- if curr.nxt == self.tail: # NEW LINE
- self.tail = curr # NEW LINE
- curr.nxt = curr.nxt.nxt
- self.count -= 1
- def delete_back(self):
- self.delete_at(-1)
- def reverse(self):
- if self.get_count() <= 1:
- return
- curr = self.head
- self.tail = self.head # NEW LINE
- f1 = curr.nxt
- f2 = f1.nxt
- self.head.nxt = None
- while f2 != None:
- f1.nxt = curr
- curr = f1
- f1 = f2
- f2 = f2.nxt
- f1.nxt = curr
- self.head = f1
- L = LinkedList()
- L.insert_back(5)
- L.insert_back(6)
- L.insert_back(7)
- L.insert_back(8)
- L.insert_front(3)
- L.insert_front(2)
- L.insert_front(1)
- print(L)
- L.reverse()
- print(L)
- L.delete_back()
- L.delete_back()
- L.delete_back()
- print(L)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement