fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cstdlib>
  4. using namespace std;
  5. typedef struct node* Node;
  6. struct node {
  7. int data;
  8. Node next;
  9. };
  10.  
  11. void swapAdjacent(Node);
  12. void print(Node);
  13. Node root;
  14. int main()
  15. {
  16. Node temp1,temp2;
  17. root=(Node)malloc(sizeof(node));
  18. root->data=1;
  19. temp1=(Node)malloc(sizeof(node));
  20. root->next=temp1;
  21. temp1->data=2;
  22. temp1->next=NULL;
  23. for(int i=3;i<=6;i++)
  24. {
  25. temp2=(Node)malloc(sizeof(node));
  26. temp1->next=temp2;
  27. temp2->data=i;
  28. temp2->next=NULL;
  29. temp1=temp1->next;
  30. }
  31. print(root);
  32. swapAdjacent(root);
  33. print(root);
  34. return 0;
  35.  
  36. }
  37.  
  38. void print(Node root)
  39. {
  40. Node temp;
  41. cout<<"\nPrinting...\n";
  42. for(temp=root;temp!=NULL;temp=temp->next)
  43. cout<<temp->data<<"\n";
  44. }
  45.  
  46. void swapAdjacent(Node head)
  47. {
  48. Node currentNode=NULL,prevNode=NULL,nextNode=NULL;
  49. bool notFirst=false;
  50. for(currentNode=head;(!notFirst) || currentNode!=NULL;currentNode=currentNode->next)
  51. {
  52. cout<<"\ncurrent node data " << currentNode->data << "\n";
  53. nextNode=currentNode->next;
  54. if(!notFirst)
  55. root=nextNode;
  56. if(notFirst)
  57. prevNode->next=nextNode;
  58. prevNode=currentNode;
  59. currentNode->next=nextNode->next;
  60. nextNode->next=currentNode;
  61. notFirst=true;
  62.  
  63. }
  64. }
Success #stdin #stdout 0.02s 2856KB
stdin
Standard input is empty
stdout
Printing...
1
2
3
4
5
6

current node data 1

current node data 3

current node data 5

Printing...
2
1
4
3
6
5