Write a function that creates a new linked list by selecting alternate elements of a given linked list.
Q.) Write a function that creates a new linked list by selecting alternate elements of a given linked list.
Subject: Data Structuresdef alternate_linked_list(head):
"""
Creates a new linked list by selecting alternate elements of a given linked list.
Args:
head: The head of the given linked list.
Returns:
The head of the new linked list.
"""
# If the given linked list is empty, return None.
if head is None:
return None
# Initialize the new linked list.
new_head = None
new_tail = None
# Iterate over the given linked list, selecting alternate elements.
while head is not None:
# If the new linked list is empty, set the new head and tail to the first element of the given linked list.
if new_head is None:
new_head = head
new_tail = head
# Otherwise, add the current element of the given linked list to the end of the new linked list.
else:
new_tail.next = head
new_tail = new_tail.next
# Move to the next element of the given linked list.
head = head.next
# Skip the next element of the given linked list.
if head is not None:
head = head.next
# Return the head of the new linked list.
return new_head
Here is a breakdown of the code:
- The
alternate_linked_list()
function takes the head of the given linked list as its argument. - It initializes the new linked list with a head and tail of
None
. - It then iterates over the given linked list, selecting alternate elements.
- If the new linked list is empty, it sets the new head and tail to the first element of the given linked list.
- Otherwise, it adds the current element of the given linked list to the end of the new linked list.
- It then moves to the next element of the given linked list.
- It skips the next element of the given linked list.
- It continues this process until it reaches the end of the given linked list.
- Finally, it returns the head of the new linked list.
The time complexity of this code is O(n)
, where n
is the number of elements in the given linked list. The space complexity is also O(n)
, since it creates a new linked list with n
elements.
Here is an example of how to use the alternate_linked_list()
function:
# Create a linked list with the values 1, 2, 3, 4, 5.
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
# Create a new linked list by selecting alternate elements of the given linked list.
new_head = alternate_linked_list(head)
# Print the values of the new linked list.
while new_head is not None:
print(new_head.data)
new_head = new_head.next
Output:
1
3
5