def reverseList(L1): reverseL1 = LinkedList() current = L1.head while current != None: reverseL1.addNode(current.value) current = current.next return reverseL1
def __init__(self, node=None): """ Initialization method for a queue object Args: node: Node object as the first element in the queue """ # Create a linked-list object with FIFO structure self.list = LinkedList(node)
def __init__(self, top=None): """ Create a stack by calling this initialization method Args: top: Node class default to None. This will be the first element in the stack """ # Stack can be implemented with linked-lists as well :D self.list = LinkedList(top)
def create_linked_list(arr: list) -> LinkedList: """ Description: Convert a python list into a custom Linked List Params: arr { list } - python list to convert Return: { LinkedList } - resulting linked list """ ll = LinkedList() for i in arr: ll.insert(i) return ll
def addLists_rev(L1, L2): p1 = L1.head p2 = L2.head carry = 0 linkedlist_sum = LinkedList() while (p1 != None) or (p2 != None) or (carry != 0): dig_sum = carry if p1 != None: dig_sum += p1.value p1 = p1.next if p2 != None: dig_sum += p2.value p2 = p2.next linkedlist_sum.addNode(dig_sum%10) carry = dig_sum/10 return linkedlist_sum
def addLists_fwd_2(L1, L2): # compare length of linked lists and pad the shorter one with 0 l1_len = lengthOfLinkedlist(L1) l2_len = lengthOfLinkedlist(L2) if l1_len < l2_len: L1 = padInFront(L1, l2_len - l1_len) else: L2 = padInFront(L2, l1_len - l2_len) # Add lists sumandcarry = addListsFwd2Helper(L1.head, L2.head) result = LinkedList() result.head = sumandcarry[0] # If the carry is not 0, insert this at the front of the linked list if sumandcarry[1] != 0: addNodeInFront(result, sumandcarry[1]) return result
def addLists_rev(L1, L2): p1 = L1.head p2 = L2.head carry = 0 linkedlist_sum = LinkedList() while (p1 != None) or (p2 != None) or (carry != 0): dig_sum = carry if p1 != None: dig_sum += p1.value p1 = p1.next if p2 != None: dig_sum += p2.value p2 = p2.next linkedlist_sum.addNode(dig_sum % 10) carry = dig_sum / 10 return linkedlist_sum
def reverseLinkedlist(linkedlist): current = linkedlist.head newlinkedlist = LinkedList() while current != None: addNodeInFront(newlinkedlist, current.value) current = current.next return newlinkedlist
class Stack: """ Stack class implementation """ def __init__(self, top=None): """ Create a stack by calling this initialization method Args: top: Node class default to None. This will be the first element in the stack """ # Stack can be implemented with linked-lists as well :D self.list = LinkedList(top) def push(self, node): """ This operation adds a node into a stack Args: node: Node class. The node is added on top of the stack in LIFO manner Returns: """ # This will add an element at the head of the linked-list self.list.append_left(node) def pop(self): """ This operation will get an element from a stack in LIFO manner Returns: Node: top node object within the stack. """ # Temporary get the top element top_element = self.list.head # Now remove the reference to the next node by calling remove method self.list.remove(top_element) # Simply return the top element return top_element def peek(self): """ You can look up the top element in O(1) time with this method without popping it out Returns: int: integer value for the top element in the stack """ # Return integer value of the top element return self.list.head.value
class Queue: """ Queue class implementation """ def __init__(self, node=None): """ Initialization method for a queue object Args: node: Node object as the first element in the queue """ # Create a linked-list object with FIFO structure self.list = LinkedList(node) def enqueue(self, node): """ This method will add an element into the queue Args: node: Node object to add into the queue Returns: """ # Append the element at the tail of the list self.list.append_right(node) def dequeue(self): """ This method will get an element from the queue in FIFO manner Returns: """ # Temporary get the head element head_element = self.list.head # Remove the head element self.list.remove(head_element) # Simply return the node object return head_element def peek(self): """ This method will return an integer value of the first element Returns: """ # Return the head element in the queue return self.list.head.value
def setUp(self): """ Setup method to initialize a linked-list Returns: """ # Create test nodes self.head_node = Node(1) self.second_node = Node(2) self.third_node = Node(3) # Create test linked-list self.list = LinkedList(self.head_node) # Append nodes such that the list is: 1->2->3 self.list.append_right(self.second_node) self.list.append_right(self.third_node)
def add1(self): # say list's head is smallest digit carrie = 0 current_node1 = l1.head current_node2 = l2.head res = LinkedList() while current_node1 or current_node2: val1 = current_node1.val if current_node1 else 0 val2 = current_node2.val if current_node2 else 0 sum_result = val1 + val2 + carrie carrie = sum_result // 10 number = sum_result % 10 res.add_node(Node(number)) current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None return res
def devide_by(self, k): smaller = LinkedList() larger = LinkedList() current_node = ll.head while current_node: inserted_node = Node(current_node.val) # 参照渡すのを防ぐため。 if current_node.val < k: last_smaller_node = inserted_node smaller.add_node(inserted_node) else: larger.add_node(inserted_node) current_node = current_node.next last_smaller_node.next = larger.head return smaller
def create_lists_and_get_height(self, root): if root == None: return 0 if root.height != None: return height else: root.height = max(self.create_lists_and_get_height(root.left), self.create_lists_and_get_height(root.right)) + 1 if not root.height in self.lists: self.lists[root.height] = LinkedList() self.lists[root.height].add_node(Node(root.value)) return root.height
def partition_list(l, x): less = LinkedList() greater = LinkedList() curr = l.head while curr.next != None: if curr.value < x: less.add_node(curr.value) else: greater.add_node(curr.value) curr = curr.next less.tail.next = greater.head less.tail = greater.tail return less
def lengthOfLinkedlist(linkedlist): length = 0 current = linkedlist.head while current != None: length += 1 current = current.next return length # -------------------test------------------ L1 = randomLinkedList(3, 3, 4) print "L2:", L1 print "isPalindrome_iter: ", isPalindrome_iter(L1) print "isPalindrome_recu: ", isPalindrome_recu(L1) L2 = LinkedList() for i in range(1,4): L2.addNode(i) for i in range(3, 0, -1): L2.addNode(i) print "L3:", L2 print "isPalindrome_iter: ", isPalindrome_iter(L2) print "isPalindrome_recu: ", isPalindrome_recu(L2) # Another method: reverse the list and check if they are the same def isPalindrome(L1): reverseL1 = reverseList(L1) return isEqual(L1, reverseL1) def reverseList(L1): reverseL1 = LinkedList()
class TestLinkedList(TestCase): """ Unit test implementation for LinkedList class """ def setUp(self): """ Setup method to initialize a linked-list Returns: """ # Create test nodes self.head_node = Node(1) self.second_node = Node(2) self.third_node = Node(3) # Create test linked-list self.list = LinkedList(self.head_node) # Append nodes such that the list is: 1->2->3 self.list.append_right(self.second_node) self.list.append_right(self.third_node) def test_append_right(self): """ Unit-test for append method in LinkedList class Returns: """ # Append new node with value of 4 such that: 1->2->3->4 current = self.list.head new_node = Node(4) self.list.append_right(new_node) # Check if all values are the same as 1 to 4 for i in range(1, 5): self.assertEqual(current.value, i) current = current.next # Check if the tail element is the new_node self.assertEqual(new_node.value, self.list.tail.value) def test_append_left(self): """ Unit-test for appending an element as the new head of the linked-list Returns: """ # Create potential head node new_node = Node(0) # Then call the function to set it as the head node self.list.append_left(new_node) # Create current node to traverse current = self.list.head # Traverse the list, then check the values for i in range(4): self.assertEqual(current.value, i) current = current.next def test_insert(self): """ Unit-test for insert method in LinkedList class Returns: """ # Insert node as the new head: 0->1->2->3 new_node = Node(0) self.list.insert(new_node, 1) # Check if correctly inserted or not self.assertEqual(self.list.head.value, new_node.value) self.assertEqual(self.list.tail.value, self.third_node.value) # Insert in the middle of the list: 0->1->5->2->3 new_node = Node(5) self.list.insert(new_node, 3) # Check if correctly inserted or not self.assertEqual(self.list.head.next.next.value, new_node.value) # Insert node as the tail of the list: 0->1->5->2->3->9 new_node = Node(9) self.list.insert(new_node, 6) # Check if correctly inserted or not self.assertEqual(self.list.tail.value, new_node.value) # Get temporary access to the list's head current = self.list.head # Get the tail node from the list while current.next: current = current.next # Check if correctly inserted or not self.assertEqual(current.value, new_node.value) self.assertEqual(current.value, self.list.tail.value) def test_search(self): """ Unit-test for search method in LinkedList class Returns: """ # Check for the head node head_node = self.list.search(1) self.assertEqual(head_node, self.head_node) # Check for the second node second_node = self.list.search(2) self.assertEqual(second_node, self.second_node) # Check for the third node third_node = self.list.search(3) self.assertEqual(third_node, self.third_node) def test_remove(self): """ Unit-test for remove method in LinkedList class Returns: """ # Remove the first node in the list: 2->3 self.list.remove(self.head_node) current = self.list.head # Check for all nodes which range from 2 to 3 for i in range(2, 4): self.assertEqual(current.value, i) current = current.next # Check is list's head is updated properly self.assertEqual(self.list.head, self.second_node) self.assertEqual(self.list.tail, self.third_node) # Remove the second node in the list: 3 self.list.remove(self.second_node) self.assertEqual(self.list.head.value, self.third_node.value) self.assertEqual(self.list.tail, self.third_node) # Remove the third node in the list, so the head should be None self.list.remove(self.third_node) self.assertIsNone(self.list.head) self.assertIsNone(self.list.tail) def test_lookup(self): """ Unit-test for lookup operation in LinkedList object Returns: """ for i in range(1, 4): self.assertEqual(self.list.lookup(i), i) def tearDown(self): """
if fast == None or fast.next == None: return None # Move one runner to head. Making them move at same pace, they will meet at the beginning of the loop fast = linkedlist.head while fast != slow: slow = slow.next fast = fast.next return fast # -----------------test------------------ nodes_number = 100 nodes_in_loop = 20 L = LinkedList() current = L.head store = [] # store nodes to help creating loop # Create a linked list for i in range(nodes_number): L.addNode(i) current = L.head if i == 0 else current.next store.append(current) # Creat loop current.next = None if nodes_in_loop <= 0 else store[nodes_number - nodes_in_loop] beginning = findBeginning(L) print beginning # 80
def __init__(self, ll): self.ll = ll def devide_by(self, k): smaller = LinkedList() larger = LinkedList() current_node = ll.head while current_node: inserted_node = Node(current_node.val) # 参照渡すのを防ぐため。 if current_node.val < k: last_smaller_node = inserted_node smaller.add_node(inserted_node) else: larger.add_node(inserted_node) current_node = current_node.next last_smaller_node.next = larger.head return smaller ll = LinkedList() ll.add_node(Node(3)) ll.add_node(Node(5)) ll.add_node(Node(4)) ll.add_node(Node(8)) ll.add_node(Node(6)) ll.add_node(Node(1)) dh = DeviderHelper(ll) print 'Defo: ' + str(ll) devided_ll = dh.devide_by(7) print 'Result: ' + str(devided_ll) # NOTE: Pythonでmutableなオブジェクトを渡している時は参照渡していると思って。
class AdditonHelper(object): def __init__(self, l1, l2): self.l1 = l1 self.l2 = l2 def add1(self): # say list's head is smallest digit carrie = 0 current_node1 = l1.head current_node2 = l2.head res = LinkedList() while current_node1 or current_node2: val1 = current_node1.val if current_node1 else 0 val2 = current_node2.val if current_node2 else 0 sum_result = val1 + val2 + carrie carrie = sum_result // 10 number = sum_result % 10 res.add_node(Node(number)) current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None return res def add2(self): # say list's head is largest digit self.res = LinkedList() self.__compensate_zeros_to_shorter() self.__add_recursively(self.l1.head, self.l2.head) return self.res def __add_recursively(self, node1, node2): val1 = node1.val val2 = node2.val if bool(node1) != bool(node2): raise Exception('Different length lists!') if node1.next == None and node2.next == None: sum_res = val1 + val2 else: sum_res = val1 + val2 + self.__add_recursively( node1.next, node2.next) number = sum_res % 10 self.res.add_node(Node(number)) carrie = sum_res // 10 return carrie def __compensate_zeros_to_shorter(self): self.__set_shorter_and_longer() for i in range(self.diff): node = Node(0) node.next = self.shorter_list.head self.shorter_list.head = node def __set_shorter_and_longer(self): current_node1 = self.l1.head current_node2 = self.l2.head self.diff = 0 while current_node1 or current_node2: if bool(current_node1) != bool(current_node2): self.shorter_list = self.l2 if current_node1 else self.l1 self.diff += 1 current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None if self.diff == 0: self.shorter_list = self.l1
node = Node(0) node.next = self.shorter_list.head self.shorter_list.head = node def __set_shorter_and_longer(self): current_node1 = self.l1.head current_node2 = self.l2.head self.diff = 0 while current_node1 or current_node2: if bool(current_node1) != bool(current_node2): self.shorter_list = self.l2 if current_node1 else self.l1 self.diff += 1 current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None if self.diff == 0: self.shorter_list = self.l1 l1 = LinkedList() l1.add_node(Node(7)) l1.add_node(Node(3)) l1.add_node(Node(6)) l1.add_node(Node(8)) l2 = LinkedList() l2.add_node(Node(6)) l2.add_node(Node(2)) ah = AdditonHelper(l1, l2) res = ah.add2() print res
class AdditonHelper(object): def __init__(self, l1, l2): self.l1 = l1 self.l2 = l2 def add1(self): # say list's head is smallest digit carrie = 0 current_node1 = l1.head current_node2 = l2.head res = LinkedList() while current_node1 or current_node2: val1 = current_node1.val if current_node1 else 0 val2 = current_node2.val if current_node2 else 0 sum_result = val1 + val2 + carrie carrie = sum_result // 10 number = sum_result % 10 res.add_node(Node(number)) current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None return res def add2(self): # say list's head is largest digit self.res = LinkedList() self.__compensate_zeros_to_shorter() self.__add_recursively(self.l1.head, self.l2.head) return self.res def __add_recursively(self, node1, node2): val1 = node1.val val2 = node2.val if bool(node1) != bool(node2): raise Exception('Different length lists!') if node1.next == None and node2.next == None: sum_res = val1 + val2 else: sum_res = val1 + val2 + self.__add_recursively(node1.next, node2.next) number = sum_res % 10 self.res.add_node(Node(number)) carrie = sum_res // 10 return carrie def __compensate_zeros_to_shorter(self): self.__set_shorter_and_longer() for i in range(self.diff): node = Node(0) node.next = self.shorter_list.head self.shorter_list.head = node def __set_shorter_and_longer(self): current_node1 = self.l1.head current_node2 = self.l2.head self.diff = 0 while current_node1 or current_node2: if bool(current_node1) != bool(current_node2): self.shorter_list = self.l2 if current_node1 else self.l1 self.diff += 1 current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None if self.diff == 0: self.shorter_list = self.l1
def add2(self): # say list's head is largest digit self.res = LinkedList() self.__compensate_zeros_to_shorter() self.__add_recursively(self.l1.head, self.l2.head) return self.res
def padInFront(linkedlist, number): padlist = LinkedList() padlist.head = linkedlist.head for i in range(number): addNodeInFront(padlist, 0) return padlist
def randomLinkedList(length, min, max): linkedlist = LinkedList() for i in range(length): value = randint(min, max) linkedlist.addNode(value) return linkedlist
node.next = self.shorter_list.head self.shorter_list.head = node def __set_shorter_and_longer(self): current_node1 = self.l1.head current_node2 = self.l2.head self.diff = 0 while current_node1 or current_node2: if bool(current_node1) != bool(current_node2): self.shorter_list = self.l2 if current_node1 else self.l1 self.diff += 1 current_node1 = current_node1.next if current_node1 else None current_node2 = current_node2.next if current_node2 else None if self.diff == 0: self.shorter_list = self.l1 l1 = LinkedList() l1.add_node(Node(7)) l1.add_node(Node(3)) l1.add_node(Node(6)) l1.add_node(Node(8)) l2 = LinkedList() l2.add_node(Node(6)) l2.add_node(Node(2)) ah = AdditonHelper(l1, l2) res = ah.add2() print res
return None # Move one runner to head. Making them move at same pace, they will meet at the beginning of the loop fast = linkedlist.head while fast != slow: slow = slow.next fast = fast.next return fast # -----------------test------------------ nodes_number = 100 nodes_in_loop = 20 L = LinkedList() current = L.head store = [] # store nodes to help creating loop # Create a linked list for i in range(nodes_number): L.addNode(i) current = L.head if i==0 else current.next store.append(current) # Creat loop current.next = None if nodes_in_loop <= 0 else store[nodes_number - nodes_in_loop] beginning = findBeginning(L) print beginning # 80
def devide_by(self, k): smaller = LinkedList() larger = LinkedList() current_node = ll.head while current_node: inserted_node = Node(current_node.val) # 参照渡すのを防ぐため。 if current_node.val < k: last_smaller_node = inserted_node smaller.add_node(inserted_node) else: larger.add_node(inserted_node) current_node = current_node.next last_smaller_node.next = larger.head return smaller ll = LinkedList() ll.add_node(Node(3)) ll.add_node(Node(5)) ll.add_node(Node(4)) ll.add_node(Node(8)) ll.add_node(Node(6)) ll.add_node(Node(1)) dh = DeviderHelper(ll) print 'Defo: ' + str(ll) devided_ll = dh.devide_by(7) print 'Result: ' + str(devided_ll) # NOTE: Pythonでmutableなオブジェクトを渡している時は参照渡していると思って。
from classes.LinkedList import * def isPalindrome(linkedlist): if linkedlist.head == None: return None fast = linkedlist.head slow = linkedlist.head firsthalf = [] while fast != None and fast.next != None: firsthalf.append(slow.value) slow = slow.next fast = fast.next.next if fast != None: slow = slow.next while slow != None: if firsthalf.pop() != slow.value: return False else: slow = slow.next return True L1 = randomLinkedList(3, 3, 4) print "L2:", L1 print "Is Palindrome? ", isPalindrome(L1) L2 = LinkedList() for i in range(1,4): L2.addNode(i) for i in range(3, 0, -1): L2.addNode(i) print "L3:", L2 print "Is Palindrome? ", isPalindrome(L2)