📜  门| GATE CS 2021 |设置 1 |问题 4(1)

📅  最后修改于: 2023-12-03 15:42:12.846000             🧑  作者: Mango

GATE CS 2021 - Set 1 - Problem 4

Introduction

Gate CS 2021 - Set 1 - Problem 4 is a programming problem that requires the programmer to write a Python program. The problem is related to Linked Lists and involves finding the intersection point of two linked lists.

Problem Description

The problem provides two singly linked lists, both of which contain n nodes. The task is to find the intersection point of these two linked lists, i.e., the node where both the linked lists merge.

Approach

One approach to solve this problem is to traverse both the linked lists and find their lengths. Then, we can calculate the difference in length and move the longer linked list's head by the difference in length so that both the linked lists have the same number of nodes to traverse.

After this, we can traverse both the linked lists together and check at which node both the linked lists meet. This node is the intersection point of the two linked lists.

Code
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node

    def get_length(self):
        temp = self.head
        count = 0
        while(temp):
            count += 1
            temp = temp.next
        return count

def find_intersection(head1, head2):
    l1 = LinkedList()
    l2 = LinkedList()
    l1.head = head1
    l2.head = head2
    len1 = l1.get_length()
    len2 = l2.get_length()
    curr1 = l1.head
    curr2 = l2.head
    diff = abs(len1-len2)
    if(len1>len2):
        for i in range(diff):
            curr1 = curr1.next
    else:
        for i in range(diff):
            curr2 = curr2.next
    while(curr1 and curr2):
        if(curr1 == curr2):
            return curr1
        curr1 = curr1.next
        curr2 = curr2.next
    return None

Conclusion

The Gate CS 2021 - Set 1 - Problem 4 is a relatively simple programming problem that involves linked lists. By combining the use of Linked Lists and simple traversal and comparison methods, one can solve this problem easily.