Good afternoon! Here's our prompt for today.
Now that we've implemented a Linked List, let's start operating on it! Assume you have a Linked List implementation with this definition:
JAVASCRIPT
1class LinkedList {
2 constructor() {
3 this.head = null;
4 this.tail = null;
5 }
6
7 prepend(newVal) {
8 const currentHead = this.head;
9 const newNode = new Node(newVal);
10 newNode.next = currentHead;
11 this.head = newNode;
12
13 if (!this.tail) {
14 this.tail = newNode;
15 }
16 }
17
18 append(newVal) {
19 const newNode = new Node(newVal);
20 if (!this.head) {
21 this.head = newNode;
22 this.tail = newNode;
23 } else {
24 this.tail.next = newNode;
25 this.tail = newNode;
26 }
27 }
28}Can you write a method getUnion to find the union of two linked lists? A union of two sets includes everything in both sets.

So given 1 -> 2 -> 3 and 3 -> 4 -> 5, we'd get 1 -> 2 -> 3 -> 4 -> 5.
Constraints
- Length of both the linkedlist <=
1000 - The nodes will always contain integer values between
-1000000000and1000000000 - Let
m, nbe the lengths of the two lists - Expected time complexity :
O(n*m) - Expected space complexity :
O(n+m)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx54
​def get_union(l1, l2): # fill in this method return l1​​# Node definitionclass Node: def __init__(self, val): self.val = val self.next = None​​def create_nodes(head, nodes): for val in nodes: new_node = Node(val) head.next = new_node head = new_node​​list1 = Node(3)nodes1 = [4, 5, 6, 7, 8, 9, 10]create_nodes(list1, nodes1)​list2 = Node(1)nodes2 = [2, 3, 4, 5, 6, 7, 8]create_nodes(list2, nodes2)​​def list_to_str(head):OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.


