现在的位置: 首页 > 综合 > 正文

Get middle element of a linked-list

2019年03月11日 ⁄ 综合 ⁄ 共 1049字 ⁄ 字号 评论关闭

Suppose there're odd number of elements in a linked-list, how to get the middle element in it? I find a clever way to achieve this on internet. Two pointers point to the linked-list. One is slow pointer and the other is quick pointer. Each time slow pointer moves one step, while the quick pointer moves two steps. When the quick pointer reaches the end of the list, the slow pointer is pointing to the middle of the list.

 

The slow and quick pointers solution can also be used to check whether there's a loop in linked list in O(n) time. If quick pointer reaches slow pointer somewhere sometime, it means there's a loop in linked list.

 

Refering to the mid function followed. It is a solution written in Haskell.

 

抱歉!评论已关闭.