138k views
3 votes
1. Create a linked list.

2. Fill in the linked list while taking input on the console, in such a way that the user enters the NUMERIC digits of their ID, one by one. For example, if we consider 123456789, then you have to insert 1 2 3 4 5 6 7 8 9 one by one, in the linked list.
3. After filling your linked list, now you need to create two other linked list one for odd numbers and the other for even numbers.
4. Now, filter out the digits individually, and put them in their respective linked list. For example, if your ID is BC123456789, then 1,3,5,7,9 would be inserted in the odd linked list while 2,4,6,8 would be inserted in the even linked list.
5. After creating two separate linked lists, merge them into a single one in such a way that the odd one should be inserted first and then the even linked list.
6. As an output, your code should display, odd digits of your id, even digits of your vu id, and then the merged list at the end .
Use only user-defined classes for Node and List, the use of struct is not allowed.

User Pumba
by
7.3k points

1 Answer

4 votes

Answer:

class Node:

def __init__(self, data):

self.data = data

self.next = None

class LinkedList:

def __init__(self):

self.head = None

def append(self, data):

new_node = Node(data)

if not self.head:

self.head = new_node

return

last_node = self.head

while last_node.next:

last_node = last_node.next

last_node.next = new_node

def display(self):

current = self.head

while current:

print(current.data, end=" ")

current = current.next

print()

def split_into_odd_and_even(self):

odd_list = LinkedList()

even_list = LinkedList()

current = self.head

while current:

if current.data % 2 == 1:

odd_list.append(current.data)

else:

even_list.append(current.data)

current = current.next

return odd_list, even_list

def merge(self, other_list):

if not self.head:

self.head = other_list.head

else:

last_node = self.head

while last_node.next:

last_node = last_node.next

last_node.next = other_list.head

def main():

main_list = LinkedList()

print("Enter the numeric digits of your ID one at a time:")

while True:

digit = input()

if not digit.isdigit():

break

main_list.append(int(digit))

odd_list, even_list = main_list.split_into_odd_and_even()

print("Odd digits:")

odd_list.display()

print("Even digits:")

even_list.display()

merged_list = odd_list

merged_list.merge(even_list)

print("Merged list:")

merged_list.display()

if __name__ == "__main__":

main()

Step-by-step explanation:

This code defines a Node class and a LinkedList class with methods to append, display, split into odd and even, and merge lists. The main function takes user input for the ID digits, creates the main linked list, splits it into odd and even lists, and then merges the two lists. The odd digits, even digits, and the merged list are displayed as output.

User Dustinmoris
by
7.8k points