Advertisement
clairec

Untitled

Jul 18th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. class DLinkedList:
  2.     def __init__(self) -> None:
  3.         self._len = 0
  4.         self._head = _Node()
  5.         self._head.next = self._head
  6.         self._head.prev = self._head
  7.         self._curr: Tuple[_Node, int] = (self._head, 1)
  8.  
  9.     def at_head(self) -> bool:
  10.         if self._curr[0] is self._head:
  11.             return True
  12.         else:
  13.             return False
  14.  
  15.     def get_curr(self) -> Tuple[Any, int]:
  16.         return (self._curr[0].data, self._curr[1])
  17.        
  18.     def set_curr(self, data: Any) -> None:
  19.         if self.at_head():
  20.             raise IndexError("Empty or curr is at head (try next or prev?)")
  21.         else:
  22.             self._curr[0].data = data
  23.  
  24.  
  25.     def next(self, n: int = 1) -> Tuple[Any, int]:
  26.         """Move the current position one forward"""
  27.         temp_node, temp_index = self._curr[0], self._curr[1]
  28.         for i in range(n):
  29.             temp_node = temp_node.next
  30.             temp_index = -1 if temp_node is self._head else temp_index + 1
  31.         self._curr = (temp_node, self._len if temp_node is self._head else temp_index)
  32.         return self.get_curr()
  33.    
  34.     def prev(self, n: int = 1) -> Tuple[Any, int]:
  35.         """Move the current position one forward"""
  36.         temp_node, temp_index = self._curr[0], self._curr[1]
  37.         for _ in range(n):
  38.             temp_node = temp_node.prev
  39.             temp_index = self._len if temp_node is self._head else temp_index - 1
  40.         self._curr = (temp_node, temp_index)
  41.         return self.get_curr()
  42.    
  43.     def __len__(self) -> int:
  44.         return self._len
  45.  
  46.     def __getitem__(self, index: int) -> Any:
  47.         tmp = self._head.next
  48.         for _ in range(index):
  49.             if tmp is self._head:
  50.                 break
  51.             else:
  52.                 tmp = tmp.next
  53.         return tmp.data
  54.  
  55.    
  56.  
  57. class _Node:
  58.     def __init__(self,
  59.                  data: Any = None,
  60.                  prev: Union[_Node, None] = None,
  61.                  next: Union[_Node, None] = None) -> None:
  62.         self.data = data
  63.         self.prev = prev
  64.         self.next = next
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement