dkanavis

rev

Nov 13th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. class Elem(object):
  5.     def __init__(self, value, next=None):
  6.         self.value = value
  7.         self.next = next
  8.  
  9.     def __str___(self):
  10.         return self.value.__str__()
  11.     def __repr__(self):
  12.         return self.value.__repr__()
  13.  
  14.  
  15.  
  16. class SList(object):
  17.     def __init__(self, l=None):
  18.         self.root = Elem(None)
  19.         if l is not None:
  20.             for elem in l:
  21.                 self.add(elem)
  22.  
  23.  
  24.     def add(self, value):
  25.         cur = self.root
  26.         while cur.next is not None:
  27.             cur = cur.next
  28.         cur.next = Elem(value)
  29.  
  30.  
  31.     def __str__(self):
  32.         return self.__repr__()
  33.  
  34.     def __repr__(self):
  35.         cur = self.root
  36.         s = ""
  37.         while True:
  38.             cur = cur.next
  39.             if cur is None:
  40.                 break
  41.             s = str(cur).join((s, ", "))
  42.  
  43.         return ''.join(("List: [", s[:-2], "]"))
  44.  
  45.  
  46.     def rev(self):
  47.         cur = self.root.next
  48.         left = None
  49.         while True:
  50.             if cur is None:
  51.                 break
  52.             right = cur.next
  53.             cur.next = left
  54.             left = cur
  55.             cur = right
  56.  
  57.         self.root.next = left
  58.  
  59.  
  60. l = SList((0, 1,2,3,4,5))
  61. print l
  62.  
  63. l.rev()
  64.  
  65. print l
Advertisement
Add Comment
Please, Sign In to add comment