Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Move last element to front of a given Linked List | Set 2
Next article icon

Reverse first K elements of given linked list

Last Updated : 22 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a pointer to the head node of a linked list and a number K, the task is to reverse the first K nodes of the linked list. We need to reverse the list by changing links between nodes. 
check also Reversal of a linked list

Examples: 

Input : 1->2->3->4->5->6->7->8->9->10->NULL, k = 3
Output : 3->2->1->4->5->6->7->8->9->10->NULL

Input : 10->18->20->25->35->NULL, k = 2
Output : 18->10->20->25->35->NULL 

Explanation of the method: 
suppose linked list is 1->2->3->4->5->NULL and k=3
1) Traverse the linked list till K-th point. 
2) Break the linked list in to two parts from k-th point. After partition linked list will look like 1->2->3->NULL & 4->5->NULL 
3) Reverse first part of the linked list leave second part as it is 3->2->1->NULL and 4->5->NULL 
4) Join both the parts of the linked list, we get 3->2->1->4->5->NULL
A pictorial representation of how the algorithm works 

 

C++




// C++ program for reversal of first k elements
// of given linked list
#include <bits/stdc++.h>
using namespace std;
 
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* Function to reverse first k elements of linked list */
static void reverseKNodes(struct Node** head_ref, int k)
{
    // traverse the linked list until break
    // point not meet
    struct Node* temp = *head_ref;
    int count = 1;
    while (count < k) {
        temp = temp->next;
        count++;
    }
 
    // backup the joint point
    struct Node* joint_point = temp->next;
    temp->next = NULL; // break the list
 
    // reverse the list till break point
    struct Node* prev = NULL;
    struct Node* current = *head_ref;
    struct Node* next;
    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
 
    // join both parts of the linked list
    // traverse the list until NULL is not
    // found
    *head_ref = prev;
    current = *head_ref;
    while (current->next != NULL)
        current = current->next;
 
    // joint both part of the list
    current->next = joint_point;
}
 
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node =
          (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
/* Function to print linked list */
void printList(struct Node* head)
{
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
}
 
/* Driver program to test above function*/
int main()
{
    // Create a linked list 1->2->3->4->5
    struct Node* head = NULL;
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
 
    // k should be less than the
    // numbers of nodes
    int k = 3;
 
    cout << "\nGiven list\n";
    printList(head);
 
    reverseKNodes(&head, k);
 
    cout << "\nModified list\n";
    printList(head);
 
    return 0;
}
 
 

Java




// Java program for reversal of first k elements
// of given linked list
class Sol
{
     
// Link list node
static class Node
{
    int data;
    Node next;
};
 
// Function to reverse first k elements of linked list
static Node reverseKNodes( Node head_ref, int k)
{
    // traverse the linked list until break
    // point not meet
    Node temp = head_ref;
    int count = 1;
    while (count < k)
    {
        temp = temp.next;
        count++;
    }
 
    // backup the joint point
    Node joint_point = temp.next;
    temp.next = null; // break the list
 
    // reverse the list till break point
    Node prev = null;
    Node current = head_ref;
    Node next;
    while (current != null)
    {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
 
    // join both parts of the linked list
    // traverse the list until null is not
    // found
    head_ref = prev;
    current = head_ref;
    while (current.next != null)
        current = current.next;
 
    // joint both part of the list
    current.next = joint_point;
    return head_ref;
}
 
// Function to push a node
static Node push( Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
 
// Function to print linked list
static void printList( Node head)
{
    Node temp = head;
    while (temp != null)
    {
        System.out.printf("%d ", temp.data);
        temp = temp.next;
    }
}
 
// Driver program to test above function
public static void main(String args[])
{
    // Create a linked list 1.2.3.4.5
    Node head = null;
    head = push(head, 5);
    head = push(head, 4);
    head = push(head, 3);
    head = push(head, 2);
    head = push(head, 1);
 
    // k should be less than the
    // numbers of nodes
    int k = 3;
 
    System.out.print("\nGiven list\n");
    printList(head);
 
    head = reverseKNodes(head, k);
 
    System.out.print("\nModified list\n");
    printList(head);
}
}
 
// This code is contributed by Arnab Kundu
 
 

Python




# Python program for reversal of first k elements
# of given linked list
 
# Node of a linked list
class Node:
    def __init__(self, next = None, data = None):
        self.next = next
        self.data = data
 
# Function to reverse first k elements of linked list
def reverseKNodes(head_ref, k) :
 
    # traverse the linked list until break
    # point not meet
    temp = head_ref
    count = 1
    while (count < k):
     
        temp = temp.next
        count = count + 1
     
    # backup the joint point
    joint_point = temp.next
    temp.next = None # break the list
 
    # reverse the list till break point
    prev = None
    current = head_ref
    next = None
    while (current != None):
     
        next = current.next
        current.next = prev
        prev = current
        current = next
     
    # join both parts of the linked list
    # traverse the list until None is not
    # found
    head_ref = prev
    current = head_ref
    while (current.next != None):
        current = current.next
 
    # joint both part of the list
    current.next = joint_point
    return head_ref
 
# Function to push a node
def push(head_ref, new_data) :
 
    new_node = Node()
    new_node.data = new_data
    new_node.next = (head_ref)
    (head_ref) = new_node
    return head_ref
 
# Function to print linked list
def printList( head) :
 
    temp = head
    while (temp != None):
     
        print(temp.data, end = " ")
        temp = temp.next
     
# Driver program to test above function
 
# Create a linked list 1.2.3.4.5
head = None
head = push(head, 5)
head = push(head, 4)
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)
 
# k should be less than the
# numbers of nodes
k = 3
 
print("\nGiven list")
printList(head)
 
head = reverseKNodes(head, k)
 
print("\nModified list")
printList(head)
 
# This code is contributed by Arnab Kundu
 
 

C#




// C# program for reversal of first k elements
// of given linked list
using System;
     
class GFG
{
     
// Link list node
public class Node
{
    public int data;
    public Node next;
};
 
// Function to reverse first k elements of linked list
static Node reverseKNodes(Node head_ref, int k)
{
     
    // traverse the linked list until break
    // point not meet
    Node temp = head_ref;
    int count = 1;
    while (count < k)
    {
        temp = temp.next;
        count++;
    }
 
    // backup the joint point
    Node joint_point = temp.next;
    temp.next = null; // break the list
 
    // reverse the list till break point
    Node prev = null;
    Node current = head_ref;
    Node next;
    while (current != null)
    {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
 
    // join both parts of the linked list
    // traverse the list until null is not
    // found
    head_ref = prev;
    current = head_ref;
    while (current.next != null)
        current = current.next;
 
    // joint both part of the list
    current.next = joint_point;
    return head_ref;
}
 
// Function to push a node
static Node push( Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
 
// Function to print linked list
static void printList( Node head)
{
    Node temp = head;
    while (temp != null)
    {
        Console.Write("{0} ", temp.data);
        temp = temp.next;
    }
}
 
// Driver Code
public static void Main(String []args)
{
    // Create a linked list 1.2.3.4.5
    Node head = null;
    head = push(head, 5);
    head = push(head, 4);
    head = push(head, 3);
    head = push(head, 2);
    head = push(head, 1);
 
    // k should be less than the
    // numbers of nodes
    int k = 3;
 
    Console.Write("Given list\n");
    printList(head);
 
    head = reverseKNodes(head, k);
 
    Console.Write("\nModified list\n");
    printList(head);
}
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
 
// Javascript program for reversal of first k elements
// of given linked list
     
// Link list node
class Node
{
    constructor()
    {
        this.data = 0;
        this.next = null;
    }
};
 
// Function to reverse first k elements of linked list
function reverseKNodes(head_ref, k)
{
     
    // traverse the linked list until break
    // point not meet
    var temp = head_ref;
    var count = 1;
    while (count < k)
    {
        temp = temp.next;
        count++;
    }
 
    // backup the joint point
    var joint_point = temp.next;
    temp.next = null; // break the list
 
    // reverse the list till break point
    var prev = null;
    var current = head_ref;
    var next;
    while (current != null)
    {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
 
    // join both parts of the linked list
    // traverse the list until null is not
    // found
    head_ref = prev;
    current = head_ref;
    while (current.next != null)
        current = current.next;
 
    // joint both part of the list
    current.next = joint_point;
    return head_ref;
}
 
// Function to push a node
function push( head_ref, new_data)
{
    var new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
 
// Function to print linked list
function printList( head)
{
    var temp = head;
    while (temp != null)
    {
        document.write(temp.data+ " ");
        temp = temp.next;
    }
}
 
// Driver Code
// Create a linked list 1.2.3.4.5
var head = null;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
// k should be less than the
// numbers of nodes
var k = 3;
document.write("Given list<br>");
printList(head);
head = reverseKNodes(head, k);
document.write("<br>Modified list<br>");
printList(head);
 
</script>
 
 

Output:  

Given list 1 2 3 4 5  Modified list 3 2 1 4 5 

Time Complexity: O(n) 
 Auxiliary Space: O(1)



Next Article
Move last element to front of a given Linked List | Set 2

S

Shahnawaz_Ali
Improve
Article Tags :
  • DSA
  • Linked List
  • Reverse
Practice Tags :
  • Linked List
  • Reverse

Similar Reads

  • Move first element to end of a given Linked List
    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. Algorithm: Traverse the list till last node. Use two pointers: one to store the
    14 min read
  • Reverse first K elements of the given Stack
    Given a stack S and an integer K, the task is to reverse the first K elements of the given stack Examples: Input: S = [ 1, 2, 3, 4, 5, 8, 3, 0, 9 ], K = 4Output: [ 4, 3, 2, 1, 5, 8, 3, 0, 9 ]Explanation: First 4 elements of the given stack are reversed Input: S = [ 1, 2, 3, 4, 5, 8, 3, 0, 9 ], K = 7
    6 min read
  • Move last element to front of a given Linked List | Set 2
    Given a singly linked list and an integer K. The task is to append last K elements of the linked list to front. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 3 Output : 4 -> 5 -> 6 -> 1 -> 2 -> 3 Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6, k = 7 Output : 6 -
    9 min read
  • Move last element to front of a given Linked List
    Given a singly linked list. The task is to move the last node to the front in a given List. Examples: Input: 2->5->6->2->1Output: 1->2->5->6->2Explanation : Node 1 moved to front. Input: 1->2->3->4->5Output: 5->1->2->3->4Explanation : Node 5 moved to f
    8 min read
  • Reverse a doubly linked list in groups of K size
    Given a Doubly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end should be considered as a group and must be reversed. Examples: Input: 1 <-> 2 <-> 3 <-> 4 <-
    15+ min read
  • Reverse a Linked List in groups of given size
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
    3 min read
  • Next greater element in the Linked List
    Given a linked list L of integers, the task is to return a linked list of integers such that it contains next greater element for each element in the given linked list. If there doesn't any greater element for any element then insert 0 for it. Examples: Input: 2->1->3->0->5 Output: 3-
    15+ min read
  • First non-repeating in a linked list
    Given a linked list, find its first non-repeating integer element. Examples: Input : 10->20->30->10->20->40->30->NULLOutput :First Non-repeating element is 40.Input :1->1->2->2->3->4->3->4->5->NULLOutput :First Non-repeating element is 5.Input :1->1
    12 min read
  • Reverse alternate K nodes in a Singly Linked List
    Given a linked list, The task is to reverse alternate k nodes. If the number of nodes left at the end of the list is fewer than k, reverse these remaining nodes or leave them in their original order, depending on the alternation pattern. Example: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -
    15+ min read
  • Reverse a Linked List in groups of given size using Deque
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences