Intersection of two Sorted Linked Lists

Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
Example:

Input: 
First linked list: 1->2->3->4->6
Second linked list be 2->4->6->8,
Output: 2->4->6.
The elements 2, 4, 6 are common in
both the list so they appear in the
intersection list.
Input:
First linked list: 1->2->3->4->5
Second linked list be 2->3->4,
Output: 2->3->4
The elements 2, 3, 4 are common in
both the list so they appear in the
intersection list.

inside class:

def get_as_list(self):
temp = self.head
stack =[]
while (temp):
stack.append(temp.data)

temp = temp.next
return stack

outside class:

def linked_list_intersection(list1,list2):
stack1 = list1.get_as_list()
stack2 = list2.get_as_list()
index = 0
new_list = Linkedlist()
for i in stack1:
if i in stack2:
if index == 0:
new_list.head = Node(i)
index+=1
else:
new_list.append_to_linked_list(i)
new_list.print_em_all()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sairam Penjarla

Sairam Penjarla

Looking for my next opportunity to make change in a BIG way