Arrays Linked Lists Questions Medium
To find the kth smallest element in a sorted linked list, we can follow the below steps:
1. Initialize two pointers, let's call them current and kthSmallest.
- Set current to the head of the linked list.
- Set kthSmallest to null.
2. Traverse the linked list until the current pointer reaches the end or kthSmallest is not null.
- Inside the loop, check if the current node's value is equal to kthSmallest.
- If it is, break the loop.
- If it's not, move the current pointer to the next node.
3. After the loop, if kthSmallest is still null, it means the linked list has fewer than k elements, so the kth smallest element doesn't exist. In this case, we can return null or throw an exception.
4. If kthSmallest is not null, it means we have found the kth smallest element in the linked list. We can return the value of kthSmallest.
Here is the implementation in Python:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def findKthSmallest(head, k):
current = head
kthSmallest = None
while current and not kthSmallest:
if current.val == k:
kthSmallest = current.val
current = current.next
if not kthSmallest:
return None
return kthSmallest
```
Note: This solution assumes that the linked list is sorted in ascending order. If the linked list is sorted in descending order, we can modify the condition in the while loop to `while current and not kthSmallest:` and the condition inside the loop to `if current.val == len(linked_list) - k + 1:`.