# Thread: successor and predecessor in doubly linked list

1. ## successor and predecessor in doubly linked list

Hello!

I was wondering if someone could help with implementation of successor and predecessor in doubly linked list. I have searched everywhere on the internet but have not fould anything useful.
My idea behind this is I look for a number which is larger than users input number but it is smaller than all other numbers. for example L = [3, 2, 7, 5, 8] if I wanna find successor for 3 it has to be bigger than 3 but smaller than other numbers which is 5.
Here is how far i've come:

insert
Code:
```struct node{
int data;
struct node *previous;
struct node *next;
};
struct node *head;
struct node *current = NULL;

struct node* successor(struct node* head, int data){

struct node* current = head;
int curr = current->data;
int temp;

while(current != NULL)
{
if(curr > data && curr < max)
{
temp = curr;
}
current = current->next;

}
}``` 2. > for example L = [3, 2, 7, 5, 8]
> if I wanna find successor for 3 it has to be bigger than 3 but smaller than other numbers which is 5.
The question is only meaningful if the list is sorted.

If L = [2, 3, 5, 7, 8] then
Code:
```while ( curr && curr->data <= 3 ) {
curr = curr->next;
}
// if curr is null, you reached the end of the list.
// otherwise, curr is pointing at the 5, which is the next lowest value that's also greater than 3``` 3. If the list is unsorted do I have to sort it in ascedning order first before I search for the successor? 4. Any idea? 5. Originally Posted by Shahiddd
My idea behind this is I look for a number which is larger than users input number but it is smaller than all other numbers.
It sounds pretty straightforward since you already have an idea: what you're doing is finding the least number greater than the given number, so a linear search of the entire linked list should do the job. The catch is that you aren't searching for an exact match, but rather you're searching for the least number that is greater than the given number.

If the linked list is already sorted, then it would of course be easier as Salem described, but if it is unsorted, sorting it first is unnecessary since you'll still need to do a linear search to find the point after the given number (but you can terminate the search immediately). 6. OK, so how should I do it if the list is unsorted? 7. I already told you: do a linear search of the entire linked list.

If you find this too difficult, try another problem first: find the smallest number in the linked list.

EDIT:
I'd also suggest renaming successor to something like successor_by_value. Normally the term "successor" as used in a linked list would simply refer to the next node, which is another reason why Salem talked about sorting, given what you're trying to find. 8. I fixed it, Thank you both for the support!  Popular pages Recent additions #### Tags for this Thread

int, node;, struct, successor, successor and predecessor 