
Problem
Solution
Submissions
Linked List Operations
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to implement a singly linked list and perform basic operations such as insertion (at the beginning, end, and a given position), deletion (at the beginning, end, and a given position), searching for an element, and printing the list.
Example 1
- Input:
- Operations:
- 1. Insert 10 at the end
- 2. Insert 20 at the end
- 3. Insert 5 at the beginning
- 4. Insert 15 at position 1
- 5. Print the list
- 6. Delete from the beginning
- 7. Delete from the end
- 8. Print the list
- 9. Search for element 15
- Operations:
- Output:
- List after operations: 5 -> 15 -> 10 -> 20
- List after deletions: 15 -> 10
- Element 15 found at position 0
- Explanation:
- Step 1: Create an empty linked list
- Step 2: Add nodes at end, beginning and specific positions
- Step 3: First deletion removes head node (5)
- Step 4: Second deletion removes tail node (20)
- Step 5: Search locates 15 at first position (index 0)
Example 2
- Input:
- Operations:
- 1. Insert 30 at the end
- 2. Insert 40 at the end
- 3. Insert 20 at the beginning
- 4. Insert 10 at the beginning
- 5. Print the list
- 6. Delete from position 2
- 7. Print the list
- 8. Search for element 40
- Operations:
- Output:
- List after operations: 10 -> 20 -> 30 -> 40
- List after deletion: 10 -> 20 -> 40
- Element 40 found at position 2
- Explanation:
- Step 1: Create an empty linked list
- Step 2: Add nodes at end and beginning
- Step 3: Delete node at position 2 (30)
- Step 4: Search locates 40 at position 2
Constraints
- 1 ≤ Number of operations ≤ 10^4
- -10^9 ≤ Element values ≤ 10^9
- Time Complexity: O(n) for insertion, deletion, and search operations
- Space Complexity: O(n) where n is the number of elements in the list
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Define a Node structure with 'data' and 'next' pointer.
- Implement a LinkedList class with a 'head' pointer.
- For insertion at the beginning, create a new node and update the head.
- For insertion at the end, traverse to the last node and update its next pointer.
- For deletion, handle special cases like an empty list or deleting the head node.
- For searching, traverse the list and compare each node's data with the target value.