Swap nodes in pairs : 2 methods
Method1: iterative approach
Start traversing from the head, swap data of each node with the data of its next node.
class node{}
void pairwiseswap(node* head)
{
node *temp= head;
//traverse only if atlest 2 nodes are left
while(temp!=NULL && temp->next!=NULL)
{
swap(temp->data, temp->next->data);
temp->next->next; //move temp by 2 units for next pair wise swap
} //while loopends
} //function ends
void push(node** head_ref, int new_data) {}
void printlist(node *head) {}
int main() {}
Recursive approach: by using a function
void pairwiseswap(struct node * head)
{
if (head!=NULL && head->next!=NULL) //if there are atleast 2 nodes
{
//swap head and head next data
swap(head->data, head->next->data);
//call pairwiseswap method/fuction for rest of list
pairwiseswap(head->next->next)
} //if ends
} //function
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home