97
Program to swap the last element of the singly linked list from the first one
Explanation
In this program we need to swap the last node of the singly linked list with the first node such that first node will become the last node and last node will become the first node.
Consider the above example; node 1 represents the head of the list and node 4 represent the last node. To swap the first node with the last node, we will iterate through the list such that index will point to second last node and current will point to the last node. Node temp will point to head. Then, make current (last node) as the new head of the list. Now, move the entire list after the old head and attach it after new head. Finally, add temp (old head node) after index node (second last node).
Algorithm
- Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
- Create another class Swap which has two attributes: head and tail.
- addNode() will add a new node to the list:
- Create a new node.
- It first checks, whether the head is equal to null which means the list is empty.
- If the list is empty, both head and tail will point to a newly added node.
- If the list is not empty, the new node will be added to end of the list such that tail’s next will point to a newly added node. This new node will become the new tail of the list.
- SwapFirstWithLast() will swap the first node with the last node:
- If the list is empty, return from the function.
- If the list is not empty, traverse through the list such that node current will point to the last node of the list and index will point to second last node.
- Check if the list contains only one node, then swapping is not possible.
- If the list contains only two nodes then, swap head node with current using node temp.
- Else, the temp will point to head, and current which was pointing to the last node will become the new head of the list.
- Move the list except for the old head node and attach it after new head, i.e. head.next = temp.next
- Now add the temp (first) node after index node to make it last node of the list and its next node will be null.
- display() will display the nodes present in the list:
- Define a node current which will initially point to the head of the list.
- Traverse through the list till current points to null.
- Display each node by making current to point to node next to it in each iteration.
Solution
Python
Output:
Originals list: 1 2 3 4 List after swapping the first node with last: 4 2 3 1
C
Output:
Originals list: 1 2 3 4 List after swapping the first node with last: 4 2 3 1
JAVA
Output:
Originals list: 1 2 3 4 List after swapping the first node with last: 4 2 3 1
C#
Output:
Originals list: 1 2 3 4 List after swapping first node with last: 4 2 3 1
PHP
Output:
Originals list: 1 2 3 4 List after swapping first node with last: 4 2 3 1
Next Topic#