Skip over navigation

Linear Search

Problems

Sequential Search on linked lists

How to Cite This SparkNote

Problem : You are given an array of linked lists (each element in the array points to a linked list), as follows:


typedef struct _list_t_ {
	int data;
	struct _list_t_ *next;
} list_t;

list_t *arr[100];
Write a function to find the largest data element in any of the lists.


int find_largest(list_t *arr[100])
{
	int i;
	list_t *list, *largest = NULL;
	for(i=0; i<100; i++) {
		for(list=arr[i]; list!=NULL; list = list->next) {
			if (largest == NULL || list->data > largest->data) largest=list;
		}
	}
	
	if (largest!=NULL) return largest->data;
	else return -1;
}

Problem : You are given a malformed linked list in which one of the list element's next pointer points back to the same element. Write a function to return a pointer to the list structure with the incorrect next pointer.


list_t *find_malformed(list_t *list)
{
	for(;list!=NULL && list->next!=list; list->next);
	return list;
}

Problem : You are given a pointer to somewhere in the middle of a doubly-linked list of integers:


typedef struct _list_t_ {
	int data;
	struct _list_t_ *next;
	struct _list_t_ *prev;
} list_t;


Find the largest element in the list.


int find_largest(list_t *list)
{
	list_t *largest;
	
	if (list==NULL) return -1;
	while(list->prev!=NULL) list = list->prev;

	for(largest=list; list!=NULL; list = list->next) {
		if (list->data > largest->data) largest=list;
	}

	return largest->data;
}

Problem : If a linked list were in sorted order, would you be able to write a search routine that worked in less than O(n) time?

No; a linked list is not a random-access data structure. In other words, even if you knew exactly where in the list the data existed, you would still have to traverse all the elements before or after to it to get to it, performing O(n) operations.

Problem : Given a singly-linked list, return a pointer to the first element whose data field is less than or equal to the data element of the last value in the list.


list_t *smaller_than_last(list_t *list)
{
	list_t *ptr;

	if (list==NULL) return NULL;

	for(ptr=list; ptr->next != NULL; ptr = ptr->next);

	for(; list!=NULL; list=list->next) {
		if (list->data <= ptr->data) return list;
	}

	return ptr;
}

Follow Us