Today's Learning: Middle Node and First and Even Node in Linked List
Hello everyone,
Today, I did two very important problems concerning Linked Lists. Here is what I focused on:
1. Middle Node of a Linked List
I started by the problem of finding the middle node in a linked list. The idea was to traverse the linked list and find the node that is in the middle.
To solve this problem, I used the two-pointer approach. I maintained two pointers: one moving one step at a time (slow) and another moving two steps at a time (fast). When the fast pointer reaches the end of the list, the slow pointer will be at the middle node. If the list has an even number of nodes, then the middle node may be the second of the two middle nodes, depending on the requirement of the problem. Thus, it allowed me to find the middle node scanning the list only once and so is efficient as well as easy to implement.
2. First and Even Node in a Linked List
The next problem I attempted asked me to find the first node with an even value in the linked list. That is, I had to traverse the list and determine whether each node contains an even value. The first such node is to be returned; if no even nodes exist, then the solution should return None.
This was pretty direct as I simply walked through the linked list and checked each node to see if its value was even. The first one whose value was even is my solution to this problem. Through this problem, I became further enlightened in traversal about conditions within linked list nodes.
I hope my experience is helpful.
Top comments (0)