Middle of a link list

R

ravi

Can any body help in finding the middle element of a link list in an
effective manner

i know the simple solution of using two pointers and increment one
pointer by one and second by two.

but i want a effective algo both in terms of memory and time
 
G

gw7rib

Can any body help in finding the middle element of a link list in an
effective manner

i know the simple solution of using two pointers and increment one
pointer by one and second by two.

but i want a effective algo both in terms of memory and time

If the structure is simply a linked list, there is no quicker way to
locate the middle element than by starting at one end and moving along
one element at a time. If the structure is a doubly linked list you
could improve on the method you have suggested slightly by starting
one pointer at the front, one at the end, and seeing where they meet -
that way you only traverse the list once instead of one and a half
times.

Hope that helps.
Paul.
 
R

ravi

If the structure is simply a linked list, there is no quicker way to
locate the middle element than by starting at one end and moving along
one element at a time. If the structure is a doubly linked list you
could improve on the method you have suggested slightly by starting
one pointer at the front, one at the end, and seeing where they meet -
that way you only traverse the list once instead of one and a half
times.

Hope that helps.
Paul.

But how i get address of the last element of the doubly link list

for eg. i am using

struct node
{
int data;
node* next;
node *previous;
};
 
B

Barry

ravi said:
But how i get address of the last element of the doubly link list

for eg. i am using

struct node
{
int data;
node* next;
node *previous;
};
The same way you get the pointer to the head of the doubly
linked list.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,685
Members
48,796
Latest member
Greg L.

Latest Threads

Top