fork download
  1. /* C program to pairwise swap elements in a given linked list */
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #define null NULL
  5. /* A linked list node */
  6. struct node
  7. {
  8. int data;
  9. struct node *next;
  10. };
  11.  
  12. struct node* swapPairs(struct node* head) {
  13. struct node *prev = head;
  14. struct node *curr;
  15. struct node *next = null, *tail = null;
  16. while(prev != null && prev->next != null) {
  17. curr = prev->next;
  18. next = curr->next;
  19. curr->next = prev;
  20. if(tail != null) tail->next = curr;
  21. else head = curr; //First two nodes are swapped. First node (previously second node) will be new head
  22. tail = prev; //Tail of lastly swapped nodes i.e. previously first one of them
  23. prev = next; //Swapping done between curr and pre, now move to next node
  24. }
  25. if(tail != null) {
  26. tail->next = prev;
  27. }
  28. return head;
  29. }
  30.  
  31. /* Function to add a node at the begining of Linked List */
  32. void push(struct node** head_ref, int new_data)
  33. {
  34. /* allocate node */
  35. struct node* new_node =
  36. (struct node*) malloc(sizeof(struct node));
  37.  
  38. /* put in the data */
  39. new_node->data = new_data;
  40.  
  41. /* link the old list off the new node */
  42. new_node->next = (*head_ref);
  43.  
  44. /* move the head to point to the new node */
  45. (*head_ref) = new_node;
  46. }
  47.  
  48. /* Function to print nodes in a given linked list */
  49. void printList(struct node *node)
  50. {
  51. while (node != NULL)
  52. {
  53. printf("%d ", node->data);
  54. node = node->next;
  55. }
  56. }
  57.  
  58. int main()
  59. {
  60. struct node *start = NULL;
  61.  
  62. /* The constructed linked list is:
  63. 2->3->4->5 */
  64. push(&start, 5);
  65. push(&start, 4);
  66. push(&start, 3);
  67. push(&start, 2);
  68. //push(&start, 1);
  69.  
  70. printf("Linked list before calling swapPairs()\n");
  71. printList(start);
  72. start = swapPairs(start);
  73.  
  74. printf("\nLinked list after calling swapPairs()\n");
  75. printList(start);
  76.  
  77. return 0;
  78. }
  79.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Linked list before calling swapPairs()

Linked list after calling swapPairs()