Swap First and Last Nodes

Swap first and last nodes in a Singly Linked List.

  • Create two node pointers: temp and lastNode
  • temp - Points to last node but one node in actual linked list.
  • lastNode - Points to last node in actual linked list.
  • Make first node in actual list as last node in resultant list.
  • Make last node in actual list as first node in resultant list.
void swapFirstAndLast(){
  struct node *temp, *lastNode;
  lastNode = head;
  while(lastNode->next!=NULL){
    temp = lastNode;
    lastNode = lastNode->next;
  }
  temp->next = head;
  lastNode->next = head->next;
  head = lastNode;
  temp->next->next = NULL;
}






Related Programs


  1. Create Singly Linked List with N number of nodes and display.
  2. Perform insertion operation on Singly Linked List.
  3. Perform deletion operation on Singly Linked List.
  4. Reverse of Singly Linked List.
  5. Move last node of Singly Linked List to first.
  6. Swap first and last nodes in a Singly Linked List.
  7. Find the length of Singly Linked List.
  8. Find middle node of Singly Linked List