Reputation: 5181
I have a Linked List and I want to implement a function:
Random_Shuffle_List (struct node **Headptr)
- which outputs a list such that every single node is randomly moved from its original position.
Please help me with an efficient algorithm to achieve this.
Upvotes: 1
Views: 7688
Reputation: 7
one way of doing this is initializing an extra field, that will contain a random number generated by a random function.
typedef struct node
{
int data;
int random;
struct node *next;
} card;
for eg, we can give
newnode->random = rand() % (100)
,which will give random numbers up to 100 to the field.Now Ordering the
linked list to ascending or descending according to the random number ,will
help us to shuffle the nodes .
for (tempnode = start; tempnode->next != NULL; tempnode = tempnode->next)
for (nextnode = tempnode->next; nextnode->next != NULL; nextnode =
nextnode->next)
{
if (tempnode->random > nextnode->random)
{
swap(tempnode, nextnode);
}
}
Upvotes: -1
Reputation: 1085
simply reverse the linked list and and swap the middle node and the end node.I think this will work.complexity would be O(n).
Upvotes: 0
Reputation: 61910
n
a
, b
) between 0
and n
a
and b
.m
times.This is not a good way, but does not require extra memory as @unwind's suggestion.
One thing could be done with @unwind's solution is by using a window.
w
w
(window) can be formedm
times.Upvotes: -1
Reputation: 399793
I would recommend the naïve approach:
This uses a relatively tiny bit of extra memory, of course, but I think it's more "efficient" in terms of time to implement (and understand) and probably also run-time, than approaches working directly on the linked list.
Upvotes: 15