Write the program to enter integer elements from user in singly linked list. User can enter both andeven values.
Question
Write the program to enter integer elements from user in singly linked list.
User can enter both odd and even values.
Solution
Here’s a simple program in Python that allows the user to enter integer elements into a singly linked list. The user can input both even and odd values.
# Node class to represent each element in the singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Singly Linked List class
class SinglyLinkedList:
def __init__(self):
self.head = None
# Function to insert a new node at the end of the list
def insert(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
# Function to display the linked list
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Main program to use the SinglyLinkedList
def main():
linked_list = SinglyLinkedList()
# Taking input from the user
n = int(input("Enter the number of elements you want to add to the linked list: "))
for i in range(n):
value = int(input("Enter an integer (even or odd): "))
linked_list.insert(value)
# Display the linked list
print("The elements in the linked list are:")
linked_list.display()
if __name__ == "__main__":
main()
Explanation:
- Node Class: Represents each element in the linked list with a data field and a pointer to the next node.
- SinglyLinkedList Class: Contains methods to insert new nodes and display the list.
- Main Function: Interacts with the user, collecting integers and building the linked list, then displays the list.
Make sure to run this program in a Python environment, and it will allow you to enter integer elements into a singly linked list.
Similar Questions
Write the program to enter integer elements from user in singly linked list. User can enter both andeven values.
Given the head pointers of two linked lists, add them and return the new linked list. Each linked list represents an integer number (each node is a digit).
Write a program to prompt user for an integer and display a triangle of stars with the same height as the input provided by the user. For example:
In a doubly linked list, the number of pointers affected for an insertion operation will be
draw the three (3) types of linked list. Make sure the elements or nodes are related to each other.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.