aboutsummaryrefslogtreecommitdiff
path: root/src/lst/ft_lstbsearch.c
blob: 25a7b4c0bffaecb828ad6650061d4d6f755aff81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_lstbsearch.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/01/30 09:17:51 by cacharle          #+#    #+#             */
/*   Updated: 2020/01/31 10:42:22 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"
#include "libft_lst.h"

static t_ftlst	*st_lstmiddle(t_ftlst *lst, t_ftlst *last)
{
	t_ftlst	*slow;
	t_ftlst	*fast;

	if (lst == NULL)
		return (NULL);
	slow = lst;
	fast = lst;
	while (fast != last)
	{
		fast = fast->next;
		if (fast == NULL)
			break ;
		slow = slow->next;
		fast = fast->next;
	}
	return (slow);
}

static t_ftlst	*st_lstbsearch_rec(t_ftlst *lst, t_ftlst *last,
						t_ftbool (*equal)(void *ref, void *content), void *ref)
{
	t_ftlst	*mid;
	t_ftlst	*left;

	if (lst == NULL)
		return (NULL);
	mid = st_lstmiddle(lst, last);
	if ((*equal)(ref, mid->content))
		return (mid);
	left = st_lstbsearch_rec(lst, mid, equal, ref);
	if (left != NULL)
		return (left);
	return (st_lstbsearch_rec(mid, NULL, equal, ref));
}

t_ftlst			*ft_lstbsearch(t_ftlst *lst,
						t_ftbool (*equal)(void *ref, void *content), void *ref)
{
	return (st_lstbsearch_rec(lst, NULL, equal, ref));
}