Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, val, nxt=None):
- self.val = val
- self.nxt = nxt
- class LinkedList:
- # construct an empty singly linked list (no tails)
- def __init__(self):
- self.head = None
- 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 < 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)
- def insert_back(self, val):
- if self.is_empty():
- self.head = Node(val, None)
- self.count += 1
- return
- curr = self.head
- while curr.nxt != None:
- curr = curr.nxt
- curr.nxt = Node(val, None)
- 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
- 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)
- curr.nxt = curr.nxt.nxt
- self.count -= 1
- def delete_back(self):
- self.delete_at(-1)
- # def delete_back(self):
- # if self.is_empty():
- # raise IndexError("deleting from an empty list")
- # if self.get_count() == 1:
- # self.head = None
- # self.count = 0
- # return
- # curr = self.get_node_at(-2)
- # curr.nxt = None
- # self.count -= 1
- def reverse(self):
- if self.get_count() <= 1:
- return
- curr = self.head
- 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)
- # print(L)
- # L.reverse()
- # print(L)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement