Beispiel #1
0
#         nextnode = list[0]
#         node = list[0]
#         while nextnode != "null":
#             node = nextnode
#             if node in seennodes:
#                 return True
#             else:
#                 seennodes.add(node)
#                 nextnode = node.values()
#
#     return False

# testing

a = Node("a", None)
b = Node("b", a)
c = Node("c", b)
d = Node("d", c)

list1 = LinkedList()
list1.append(a)
list1.prepend(b)
list1.prepend(c)
list1.prepend(d)

print(list1)

# print(containscycle(list2))  #false
# print(containscycle(list3))  #false
# print(containscycle(list4))  #false
Beispiel #2
0
 def setUp(self):
     self.linked_list = LinkedList()
from random import randrange
from LinkedList import LinkedList

linkedList = LinkedList()

for i in range(10):
    linkedList.insertEnd(randrange(0, 10))
linkedList.insertStart(123)
print("t1")
linkedList.traverseList()
print("size:", linkedList.size())

linkedList.remove(123)

print("t2")
linkedList.traverseList()
print("size:", linkedList.size())

linkedList.insertIndex(2, 100)

print("t3")
linkedList.traverseList()
print("size:", linkedList.size())

print("element 3: ", linkedList.index(2))
Beispiel #4
0
    def reverseListRecur(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            # Return the last node in the list all the way back to the beginning
            return head
        node = self.reverseListRecur(head.next)
        # In the present node, set the node after it from the original list
        # equal to the present node. (i.e., reverse the node ahead of the present one)
        head.next.next = head
        head.next = None
        return node


if __name__ == "__main__":
    from LinkedList import LinkedList
    linked = LinkedList()
    for c in "string":
        linked.add(c)

    print("Before")
    linked.displayList()

    obj = Solution()
    # linked.head = obj.reverseList(linked.head)
    linked.head = obj.reverseListRecur(linked.head)
    print("After")
    linked.displayList()
    """
    # if linked-list is empty
    if not linked_list.head or not linked_list.head.next:
        return False

    slow = fast = linked_list.head

    while fast and fast.next:
        slow = slow.next  #slow takes one step at a time
        fast = fast.next.next  #fast takes two step at a time

        #if slow meets with fast that means linked-list is cyclic
        if fast == slow:
            return True
    return False


linked_list = LinkedList()
linked_list.insert_end(1)
linked_list.insert_end(2)
linked_list.insert_end(3)
linked_list.insert_end(4)
linked_list.insert_end(5)
linked_list.insert_end(6)

#making the linked-list cyclic
linked_list.tail.next = linked_list.head

result = is_cyclic(linked_list)
print(result)
Beispiel #6
0
    )
    print('4.Enter d to delete a list')
    print(
        '5.Enter m to merge two lists into a binary list and transform it to a decimal number'
    )
    print('6.Enter e to exit menu')


def random_list(size, lower_bound, higher_bound):
    new_linked_list = LinkedList()
    for z in range(0, size):
        new_linked_list.prepend(random.randint(lower_bound, higher_bound))
    return new_linked_list


tester = LinkedList()
available_linked_lists = []
while True:
    menu()
    user_choice = input()

    if user_choice == 'e':
        break

    elif user_choice == 'a':
        try:
            new_list_size = int(input('Enter the size of a new linked list: '))
            lower_end = int(
                input('Enter the lower end of possible random numbers: '))
            higher_end = int(
                input('Enter the higher end of possible random numbers: '))
Beispiel #7
0
def sum_lists_followup(first_list: LinkedList, second_list: LinkedList) -> LinkedList:
    (first_list, second_list) = zero_pad_if_different_lengths(first_list, second_list)
    result_list = LinkedList()
    (result_list, carryover) = calculate_sum_lists(first_list.head, second_list.head, 0, result_list)
    return result_list
Beispiel #8
0
def LLInit():
    ll = LinkedList()
    return True
Beispiel #9
0
def LLLen_1():
    ll = LinkedList([1, 2, 3])
    if len(ll) == 3:
        return True
    return False
Beispiel #10
0
 def test_append(self):
     """测试添加节点(尾部)"""
     link = LinkedList(head)
     node1 = Node(2)
     link.append_element(node1)
     self.assertTrue(link.get_size() == 2)
Beispiel #11
0
 def test_index(self):
     """测试链表结构的正确性(一个节点指向下一个节点)"""
     link = LinkedList(head)
     link.append_element(2)
     link.append_element(3)
     self.assertTrue(link.get_size() == 3)
Beispiel #12
0
 def test_size(self):
     """测试获取链表大小"""
     link1 = LinkedList(head)
     self.assertTrue(link1.get_size() == 1)
"""Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?"""

#O(N^2)
from LinkedList import LinkedList
def remove_duplicates(list_):
  head = list_.head
  while head.next:
    temp = head.value
    temp_head = head
    while temp_head.next:
      if temp_head.next.value == temp:
        temp_head.next = temp_head.next.next
      else:
        temp_head = temp_head.next
      if head == None: break    
    head = head.next
    if head == None: break
  return list_


if __name__ == '__main__':
  list_ = LinkedList()
  list_.generate(40, 0, 8)
  print(list_)
  list_ = remove_duplicates(list_)
  print(list_)
Beispiel #14
0
        return True
    elif all(counter[val] % 2 == 0 for val in counter if val != middle_value):
        return True
    else:
        return False


def count_length(ll):
    val = ll.head
    length = 1
    while val.next != None:
        length += 1
        val = val.next
    return length


ll_true = LinkedList([1, 2, 3, 4, 5, 4, 3, 2, 1])
print(is_palindrome(ll_true))
print 'Should be true', '\n'

ll_true2 = LinkedList([1, 4, 6, 6, 4, 1])
print(is_palindrome(ll_true2))
print 'Should be true', '\n'

ll_true3 = LinkedList([1, 4, 6, 2, 6, 4, 1])
print(is_palindrome(ll_true3))
print 'Should be true', '\n'

ll_false = LinkedList([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(is_palindrome(ll_false))
print 'Should be false', '\n'
Beispiel #15
0
def kidx_to_n(inp, kth_idx):
    curr = inp.head
    for i in range(0, kth_idx):
        if not curr:
            return None
        else:
            curr = curr.next
    inp.head = curr
    return inp


def kval_to_n(inp, kth_val):
    curr = inp.head
    while curr:
        if curr.value == kth_val:
            break
        else:
            curr = curr.next
    inp.head = curr
    return inp


random_num = LinkedList().generate(10, 1, 100)
print(random_num)
print(kidx_to_n(random_num, 4))
print('')
random_num = LinkedList().generate(20, 1, 5)
print(random_num)
print(kval_to_n(random_num, 4))
Beispiel #16
0
    while node1 is not None or node2 is not None:
        value1 = node1.value if node1 is not None else 0
        value2 = node2.value if node2 is not None else 0

        value = value1 + value2 + carry
        result.add_to_tail(value % 10)
        carry = 1 if value/10 >= 1 else 0

        if node1 is not None:
            node1 = node1.next
        if node2 is not None:
            node2 = node2.next

    return result


ll1 = LinkedList()
ll2 = LinkedList()

ll1.add_to_tail(1)
ll1.add_to_tail(2)
ll1.add_to_tail(3)

ll2.add_to_tail(8)
ll2.add_to_tail(9)

result = add_lists(ll1.top, ll2.top)
print(result.top.value)
print(result.top.next.value)
print(result.top.next.next.value)
Beispiel #17
0
def loop_detection(ll):
    fast = slow = ll.head

    while fast and fast.next:
        fast = fast.next.next
        slow = slow.next
        if fast is slow:
            break

    if fast is None or fast.next is None:  # no loop
        return None

    slow = ll.head
    while fast is not slow:
        fast = fast.next
        slow = slow.next

    return fast


if __name__ == '__main__':
    ll = LinkedList([3, 1, 5, 9, 7, 2, 1])
    count = 3
    current = ll.head
    for i in range(count):
        current = current.next
    ll.tail.next = current
    print loop_detection(ll)

Beispiel #18
0
 def __init__(self, capacity):
     if capacity < MIN_CAPACITY:
         capacity = MIN_CAPACITY
     self.capacity = capacity
     self.storage = [LinkedList()] * capacity
     self.count = 0
Beispiel #19
0
def random_list(size, lower_bound, higher_bound):
    new_linked_list = LinkedList()
    for z in range(0, size):
        new_linked_list.prepend(random.randint(lower_bound, higher_bound))
    return new_linked_list
Beispiel #20
0
from P_match import p_match as pm
from Queue import Queue
from LinkedList import LinkedList

# exp = "[5-(4*6)+{3(6-4)[3]}]"
# if pm(exp):
#     print("Valid")
# else:
#     print("Invalid")

# q = Queue("1")
# q.insert_at_rear("2")
# q.insert_at_rear("3")
# q.insert_at_rear("4")
# q.insert_at_rear("2")
# q.insert_at_rear("3")
# q.insert_at_rear("4")

x = LinkedList("z")
x.insert_as_head("ss")
print(x.delete_head())
Beispiel #21
0
def check_if_intersects(lines_list, max_y):
    lines_dictionary, q = read_lines_list(lines_list)

    start_points_used_dictionary = dict()
    end_points_used_dictionary = dict()
    for line in lines_dictionary:
        start_points_used_dictionary[line] = False
        end_points_used_dictionary[line] = False

    lines_collection = LinesCollection(lines_list)
    my_scene = Scene([], [lines_collection])
    my_plot = Plot([my_scene])

    #print("\n\nLines:")
    #for line in lines_list:
    #    print(line)

    t = LinkedList(lines_dictionary)
    intersections_dictionary = dict()
    prev_point = None
    prev_line = None
    # Q: x->y
    while q.size > 0:
        event = q.findTheSmallest(q.root)
        point = (event.key, event.value)

        #print("\n-------------------------------------------------\n" + str(point), end="")
        # update T
        begin_line = is_start_point_checked(start_points_used_dictionary,
                                            point)
        end_line = []
        if begin_line is None:
            end_line = is_end_point_checked(end_points_used_dictionary, point)

        if begin_line is not None:
            handle_line_begin_event(begin_line, t)
            #print("found line: " + str(begin_line))

        elif end_line is not None:
            handle_line_end_event(end_line, t)
            #print("found line: " + str(end_line))

        else:  # intersection point
            handle_intersection_event(lines_dictionary, point, t,
                                      intersections_dictionary)

        # handle two line ends in the same point
        if prev_point == point:
            if end_line:
                #print("Two ends intersection in: " + str(point))
                intersections_dictionary[point] = (prev_line, end_line)

        # update Q
        look_for_intersections(lines_dictionary, point, t, q,
                               intersections_dictionary)

        q.delete(event.key, event.value)
        prev_line = end_line
        prev_point = point

    #print("\nintersections number: " + str(len(intersections_dictionary)))
    for intersection in intersections_dictionary:
        point = intersection
        line1 = intersections_dictionary[intersection][0]
        line2 = intersections_dictionary[intersection][1]
        #print(str(point) + " is intersection of " + str(line1) + " and " + str(line2))

        new_line = [(point[0], max_y), (point[0], 1)]
        new_lines_collection = LinesCollection([new_line], color="red")
        points_collection = PointsCollection([point],
                                             color="green",
                                             marker="^")
        new_scene = Scene([points_collection],
                          [lines_collection, new_lines_collection])
        my_plot.add_scene(new_scene)

    my_plot.draw()
    return intersections_dictionary
Beispiel #22
0
 def __init__(self):
     self.__lst = LinkedList()
     self.__strategy = None
Beispiel #23
0
#! /usr/bin/env python

from LinkedList import Node, LinkedList

def find_loop(list1):
    nodes = []
    for n in list1:
        if n in nodes:
            return n
        nodes.append(n)
    return None

node1 = Node(2)
node2 = Node(8)
node3 = Node(5)
node4 = Node(3)
node5 = Node(10)
node6 = Node(4)

link1 = LinkedList()

link1.insert(node1)
link1.insert(node2)
link1.insert(node2)
link1.insert(node3)
link1.insert(node4)
link1.insert(node5)
link1.insert(node6)
link1.insert(node3)

print("is loop {0}".format(find_loop(link1)))
Beispiel #24
0
# Prompt: Implement a function to check if a linked list is a palindrome
from LinkedList import LinkedList


def palindrome(ll: LinkedList) -> bool:
    vals = ll.get_vals()
    mid = int(len(vals) / 2)
    left = vals[:mid]
    right = vals[mid:][::-1]
    if len(vals) % 2 == 1:
        right.pop()
    return left == right


test1 = LinkedList('m')
test1.append('o')
test1.append('o')
test1.append('m')

test2 = LinkedList('a')
test2.append('a')
test2.append('a')

test3 = LinkedList('a')
test3.append('a')
test3.append('b')

assert (palindrome(test1) == True)
assert (palindrome(test2) == True)
assert (palindrome(test3) == False)
# EX: input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition = 5]
#    output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8

from LinkedList import LinkedList


def partition(ll, x):
    current = ll.tail = ll.head
    print current

    while current:
        nextNode = current.next
        current.next = None
        if current.value < x:
            current.next = ll.head
            ll.head = current
        else:
            ll.tail.next = current
            ll.tail = current
        current = nextNode

    # Error check in case all nodes are less than x
    if ll.tail.next is not None:
        ll.tail.next = None


ll = LinkedList()
ll.generate(10, 0, 99)
print(ll)
partition(ll, ll.head.value)
print(ll)
Beispiel #26
0
from random import randint

from LinkedList import LinkedList


def get_value(l):
    ans = 0
    for i, val in enumerate(l):
        # giv digits value in reverse order (3->4->5) = 543
        ans += val * (10**i)
    return ans


# example given
list1 = LinkedList()
list1.add(3)
list1.add(1)
list1.add(5)

list2 = LinkedList()
list2.add(5)
list2.add(9)
list2.add(2)

print(list1, list2)
print(get_value(list1), "+", get_value(list2), "=",
      get_value(list1) + get_value(list2))
print()

# random test
l1, l2 = LinkedList(), LinkedList()
Beispiel #27
0
 def create_arr(self, size):
     arrayList = []
     for i in range(0, size):
         arrayList.append(LinkedList())
     return arrayList
Beispiel #28
0
 def __init__(self):
     self.items = LinkedList()
Beispiel #29
0
def generate_test_linked_list(length):
    linked_list = LinkedList()
    for i in range(length, 0, -1):
        linked_list.insert_beginning(i)
    return linked_list
Beispiel #30
0
            newnode.next = temp
            temp = newnode
        else:
            temp = newnode
        head = head.next
    return temp


def is_palindrome(head):
    rev = reverse(head)
    while head:
        if rev.data != head.data:
            return False
        rev = rev.next
        head = head.next
    return True


obj = LinkedList()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(4)
obj.add(3)
obj.add(2)
# obj.add(2)
obj.add(1)
# obj.add(1)

print(is_palindrome(obj.head))