I am trying to swap two adjacent nodes in a linked list, and I think I understand the idea of how to do it using a temporary node.
Here is my struct swap function
struct part {
char* name;
float price;
int quantity;
struct part *next;
};
typedef struct part partType;
partType *swap_node(partType **item) {
partType *temp;
temp = *item;
*item = (*item)->next;
temp->next = (*item)->next;
(*item)->next = temp;
return *item;
}
I cant think of how to make the previous node in the list point to the new swapped node. Do i need another temp variable? Also, how do I account for the case that the two nodes to be swapped are the first two in the list.
From the code, it looks like you want to swap item and item->next.
If you don’t have a doubly-linked list, then you need to set linkPtr to head, and then iterate until linkPtr->next == *item. From there, you can start switching between linkPtr, linkPtr->next and linkPtr->next->next.
You also need a separate condition comparing linkPtr to head, and if so, then you need to set head to the new head.