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;
}
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
- Create Singly Linked List with N number of nodes and display.
- Perform insertion operation on Singly Linked List.
- Perform deletion operation on Singly Linked List.
- Reverse of Singly Linked List.
- Move last node of Singly Linked List to first.
- Swap first and last nodes in a Singly Linked List.
- Find the length of Singly Linked List.
- Find middle node of Singly Linked List