Write a C function that moves first element to end in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 2->3->4->5->1.
Traverse the list till last node. Use two pointers: one to store the address of last node(last) and other for address of first node(first). After the end of loop do following operations.
i) Make head as second node (*head_ref = first->next).
ii) Set next of first as NULL (first->next = NULL).
iii) Set next of last as first ( last->next = first)
Linked list before moving first to end 1 2 3 4 5 Linked list after moving first to end 2 3 4 5 1
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Write a function to get the intersection point of two Linked Lists.
- Doubly Linked List | Set 1 (Introduction and Insertion)
- Count pairs in a binary tree whose sum is equal to a given value x
- Mu Sigma Interview On Campus
- Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment
- Bubble Sort On Doubly Linked List
- Reverse nodes of a linked list without affecting the special characters
- Applications of linked list data structure
- Amazon SDE-2 Interview Experience
- Flatten a binary tree into linked list | Set-2