-
Linked List swap
Hi;
Was working on a question. The question was to write a function that will swap a element in the list with next element in the list. I can get it to work for first element in the list but not for an element in the middle of the list.
Any ideas?
This is not a homework question or anything like it, jsut something i am doing myself.
Thanks
-
Re: Linked List swap
.....code it correctly?
What are you looking for here?
-
Re: Linked List swap
basically looking for code where it will swap any element in the list with the next element!
For example a link list like:
1-2-3-4-5
lets swap 3 with 4 so we have
1-2-4-3-5
But i dont want to create a new link list
-
Re: Linked List swap
If this is a singly linked list, then you would need to change the next pointers of the second, third and fourth elements in order to efficiently swap the third and fourth elements in the list.
-
Re: Linked List swap
Show us what you tried, and we'll help you find the problem.
-
Re: Linked List swap
<code>
struct node *swapPairs( node *l)
{
if(start_ptr==NULL)
{
Cout<<”List is NULL”<<endl;
}
Else
{
node *current = start_ptr;
while(current->next!=l)
current = current->next;
node *temp = current->next; //temp = next node;
node *prev = current; //prev = current node;
current = temp; //current now = next node value;
current->next=prev; //current next now = current old value
}
Return start_ptr;
}
</code>
-
Re: Linked List swap
Good try, but you use square brackets [] for code tags here.
Let's see....
1) You've got a few things capitalized there which shouldn't be.
2) What is this "l" parameter? I see you referencing start_ptr, should that be a parameter as well? Usually the name of the function and the parameter list should suggest its usage, but if I see a function called "swapPairs" that takes a single pointer, I'm going to be very confused about what I'm supposed to give it.
3) As you observed, using this approach a special case is required to handle the first element of the list. You could get around that by defining a node** which initially points to start_ptr and then later points to the given current->next....
4) By definition, temp == l. You don't really need two names for the same node.
5) Here's your big problem: "current = temp". You've modified your local variable current, but you haven't modified the list at all there! If you intend to swap "current" and "temp", then you'll need to modify current->next, temp->next, *and* the node prior to current's next pointer. Try drawing a diagram to see why.
-
Re: Linked List swap
Thanks for that.
I will mess around with it again tomorrow, and if any problems will post back.
Thanks
-
Re: Linked List swap
If this is not practice but something you need in reality then use std::list and splice.