SHARE
TWEET

Untitled

a guest Oct 21st, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Node:
  2.   def __init__(self, data):
  3.     self.data = data
  4.     self.next = None
  5.  
  6. class LinkedList:
  7.   def __init__(self):
  8.     self.head = None
  9.  
  10.   # print list of linked list
  11.   def print_list(self):
  12.     cur_node = self.head
  13.     while cur_node:
  14.       print(cur_node.data)
  15.       cur_node = cur_node.next
  16.  
  17.   # add to end of linked list
  18.   def append(self, data):
  19.     new_node = Node(data)
  20.     cur = self.head
  21.  
  22.     if self.head is None:
  23.       self.head = new_node
  24.       return
  25.  
  26.     while cur.next:
  27.       cur = cur.next
  28.     cur.next = new_node
  29.  
  30.   def prepend(self, data):
  31.     new_node = Node(data)
  32.     new_node.next = self.head
  33.     self.head = new_node
  34.  
  35.   def reverse_iterative(self):
  36.  
  37.     prev = None
  38.     cur = self.head
  39.     while cur:
  40.         nxt = cur.next
  41.         cur.next = prev
  42.  
  43.         prev = cur
  44.         cur = nxt
  45.     self.head = prev
  46.  
  47.  
  48. ll = LinkedList()
  49. ll.append("A")
  50. ll.append("B")
  51. ll.append("C")
  52. ll.append("D")
  53. ll.prepend("E")
  54. print("given")
  55. ll.print_list()
  56. print("reversed list")
  57. ll.reverse_iterative()
  58. ll.print_list()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top