compare two linked list python

Solutions on MaxInterview for compare two linked list python by the best coders in the world

showing results for - "compare two linked list python"
Gianluca
06 Jan 2021
1class SinglyLinkedListNode:
2    def __init__(self, node_data):
3        self.data = node_data
4        self.next = None
5
6
7class SinglyLinkedList:
8    def __init__(self):
9        self.head = None
10        self.tail = None
11
12    def insert_node(self, node_data):
13        node = SinglyLinkedListNode(node_data)
14
15        if not self.head:
16            self.head = node
17        else:
18            self.tail.next = node
19
20        self.tail = node
21
22
23def print_singly_linked_list(node, sep, fptr):
24    while node:
25        fptr.write(str(node.data))
26
27        node = node.next
28
29        if node:
30            fptr.write(sep)
31
32
33def printt(headd):
34    itr = headd
35    llstr = []
36    while itr:
37        llstr.append(itr.data)
38        itr = itr.next
39    return llstr
40
41
42def compare_lists(llist1, llist2):
43    ll1 = printt(llist1)
44    ll2 = printt(llist2)
45    if ll1 == ll2:
46        return 'Same'
47    else:
48        return 'Not Same'
49
50
51if __name__ == '__main__':
52
53    llist1_count = int(input("Number of nodes in LinkedList1: "))
54
55    llist1 = SinglyLinkedList()
56    print("Enter the value to be stored on linkedlist 1: ")
57    for _ in range(llist1_count):
58        llist1_item = input()
59        llist1.insert_node(llist1_item)
60
61    print('\n')
62    llist2_count = int(input("Number of nodes in LinkedList2: "))
63
64    llist2 = SinglyLinkedList()
65
66    print("Enter the value to be stored on linkedlist 2: ")
67    for _ in range(llist2_count):
68        llist2_item = input()
69        llist2.insert_node(llist2_item)
70
71    result = compare_lists(llist1.head, llist2.head)
72
73    print('Result:', result)
74
75    '''
76    Explanation 1:
77    ----------------------------------------------
78    Input format:
79    Number of nodes in LinkedList1: 2
80    Enter the value to be stored on linkedlist 1:
81    1
82    2
83    Number of nodes in LinkedList2: 2
84    Enter the value to be stored on linkedlist 2:
85    1
86    2
87    -------------------------------------------------
88    Output:
89    Result: Same
90    --------------------------------------------------
91    Explanation 2:
92    ----------------------------------------------
93    Input format:
94    Number of nodes in LinkedList1: 2
95    Enter the value to be stored on linkedlist 1:
96    1
97    2
98    Number of nodes in LinkedList2: 2
99    Enter the value to be stored on linkedlist 2:
100    2
101    1
102    -------------------------------------------------
103    Output:
104    Result: Not Same
105    --------------------------------------------------
106    '''