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
  • Data Structures
  • Array
  • String
  • Linked List
  • Stack
  • Queue
  • Tree
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Graph
  • Trie
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • AVL Tree
  • Red-Black Tree
  • Advanced Data Structures
Open In App
Next Article:
Insert a Node at the end of Doubly Linked List
Next article icon

Insert Node at the End of a Linked List

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a linked list, the task is to insert a new node at the end of the linked list.

Examples:

Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1
Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1

Input: LinkedList = NULL, NewNode = 1
Output: LinkedList = 1

Approach: 

Inserting at the end involves traversing the entire list until we reach the last node. We then set the last node's next reference to point to the new node, making the new node the last element in the list.

Insertion-at-the-End-of-Singly-Linked-List

Following is the approach to add a new node at the end of the linked list:

  • Create a new node and set its next pointer as NULL since it will be the last node.
  • Store the head reference in a temporary variable
  • If the Linked List is empty, make the new node as the head and return
  • Else traverse till the last node
  • Change the next pointer of the last node to point to the new node

Below is the implementation of the approach:

C++
#include <iostream> using namespace std;  // A linked list node class Node { public:     int data;     Node* next;      // Constructor to initialize a new node with data     Node(int new_data) {         data = new_data;         next = nullptr;     } };  // Given the head of a list and an int, appends // a new node at the end and returns the head. Node* append(Node* head, int new_data) {        // Create a new node     Node* new_node = new Node(new_data);      // If the Linked List is empty, make     // the new node as the head and return     if (head == nullptr) {         return new_node;     }      // Store the head reference in a temporary variable     Node* last = head;      // Traverse till the last node     while (last->next != nullptr) {         last = last->next;     }      // Change the next pointer of the last node      // to point to the new node     last->next = new_node;      // Return the head of the list     return head; }  // This function prints the contents  // of the linked list starting from the head void printList(Node* node) {     while (node != nullptr) {         cout << " " << node->data;         node = node->next;     } }  // Driver code int main() {        // Create a hard-coded linked list:     // 2 -> 3 -> 4 -> 5 -> 6     Node* head = new Node(2);     head->next = new Node(3);     head->next->next = new Node(4);     head->next->next->next = new Node(5);     head->next->next->next->next = new Node(6);      cout << "Created Linked list is:";     printList(head);      // Example of appending a node at the end     head = append(head, 1);      cout << "\nAfter inserting 1 at the end:";     printList(head);      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  // A linked list node struct Node {     int data;     struct Node* next; };  // Function to create a new node struct Node* createNode(int new_data) {     struct Node* new_node =         (struct Node*)malloc(sizeof(struct Node));     new_node->data = new_data;     new_node->next = NULL;     return new_node; }  // Given the head of a list and an int, appends // a new node at the end and returns the head. struct Node* append(struct Node* head, int new_data) {        // Create a new node     struct Node* new_node = createNode(new_data);      // If the Linked List is empty, make     // the new node as the head and return     if (head == NULL) {         return new_node;     }      // Store the head reference in a temporary variable     struct Node* last = head;      // Traverse till the last node     while (last->next != NULL) {         last = last->next;     }      // Change the next pointer of the last node      // to point to the new node     last->next = new_node;      // Return the head of the list     return head; }  // This function prints the contents  // of the linked list starting from the head void printList(struct Node* node) {     while (node != NULL) {         printf(" %d", node->data);         node = node->next;     } }  // Driver code int main() {        // Create a hard-coded linked list:      // 2 -> 3 -> 4 -> 5 -> 6     struct Node* head = createNode(2);     head->next = createNode(3);     head->next->next = createNode(4);     head->next->next->next = createNode(5);     head->next->next->next->next = createNode(6);      printf("Created Linked list is:");     printList(head);      // Example of appending a node at the end     head = append(head, 1);      printf("\nAfter inserting 1 at the end:");     printList(head);      return 0; } 
Java
class Node {     int data;     Node next;      // Constructor to initialize a new node with data     Node(int newData) {         data = newData;         next = null;     } }  public class GfG {          // Given the head of a list and an int, appends     // a new node at the end and returns the head.     static Node append(Node head, int newData) {                // Create a new node         Node newNode = new Node(newData);          // If the Linked List is empty, make the new          // node as the head and return         if (head == null) {             return newNode;         }          // Store the head reference in a temporary variable         Node last = head;          // Traverse till the last node         while (last.next != null) {             last = last.next;         }          // Change the next pointer of the          // last node to point to the new node         last.next = newNode;          // Return the head of the list         return head;     }      // This function prints the contents of      // the linked list starting from the head     public static void printList(Node node) {         while (node != null) {             System.out.print(" " + node.data);             node = node.next;         }     }      // Driver code     public static void main(String[] args) {                // Create a hard-coded linked list:          // 2 -> 3 -> 4 -> 5 -> 6         Node head = new Node(2);         head.next = new Node(3);         head.next.next = new Node(4);         head.next.next.next = new Node(5);         head.next.next.next.next = new Node(6);          System.out.print("Created Linked list is:");         printList(head);          // Example of appending a node at the end         head = append(head, 1);          System.out.print("\nAfter inserting 1 at the end:");         printList(head);     } } 
Python
class Node:     def __init__(self, data):         self.data = data         self.next = None   # Given the head of a list and an int, appends # a new node at the end and returns the head. def append(head, new_data):      # Create a new node     new_node = Node(new_data)      # If the Linked List is empty, make the      # new node as the head and return     if head is None:         return new_node      # Store the head reference in a temporary variable     last = head      # Traverse till the last node     while last.next:         last = last.next      # Change the next pointer of the last      # node to point to the new node     last.next = new_node      # Return the head of the list     return head   # This function prints the contents of the  # linked list starting from the head def print_list(node):      while node:         print(node.data, end=" ")         node = node.next   # Driver code if __name__ == "__main__":      # Create a hard-coded linked list:      # 2 -> 3 -> 4 -> 5 -> 6     head = Node(2)     head.next = Node(3)     head.next.next = Node(4)     head.next.next.next = Node(5)     head.next.next.next.next = Node(6)      print("Created Linked list is: ", end="")     print_list(head)      # Example of appending a node at the end     head = append(head, 1)      print("\nAfter inserting 1 at the end: ", end="")     print_list(head) 
C#
using System;  public class Node {     public int data;     public Node next;      // Constructor to initialize a new node with data     public Node(int newData)     {         data = newData;         next = null;     } }  // Appends a new node at the end  // and returns the head. public class GfG {     public static Node Append(Node head, int newData)     {         // Create a new node         Node newNode = new Node(newData);          // If the Linked List is empty,         // make the new node as the head         if (head == null)         {             return newNode;         }          // Store the head reference in a          // temporary variable         Node last = head;          // Traverse till the last node         while (last.next != null)         {             last = last.next;         }          // Change the next pointer of the          // last node to point to the new node         last.next = newNode;          // Return the head of the list         return head;     }      // Prints the contents of the linked     // list starting from the head     public static void PrintList(Node node)     {         while (node != null)         {             Console.Write(node.data + " ");             node = node.next;         }     }      // Driver code     public static void Main(string[] args)     {         // Create a hard-coded linked list:         // 2 -> 3 -> 4 -> 5 -> 6         Node head = new Node(2);         head.next = new Node(3);         head.next.next = new Node(4);         head.next.next.next = new Node(5);         head.next.next.next.next = new Node(6);          Console.Write("Created Linked list is: ");         PrintList(head);          // Example of appending a node          // at the end         head = Append(head, 1);          Console.Write("\nAfter inserting 1 at the end: ");         PrintList(head);     } } 
JavaScript
class Node {     constructor(data) {         this.data = data;         this.next = null;     } }  // Appends a new node at the end  // and returns the head. function append(head, newData) {      // Create a new node     const newNode = new Node(newData);      // If the Linked List is empty,     // make the new node as the head     if (head === null) {         return newNode;     }      // Store the head reference in a      // temporary variable     let last = head;      // Traverse till the last node     while (last.next !== null) {         last = last.next;     }      // Change the next pointer of the      // last node to point to the new node     last.next = newNode;      // Return the head of the list     return head; }  // Prints the contents of the linked // list starting from the head function printList(node) {     while (node !== null) {         console.log(node.data + " ");         node = node.next;     } }  // Create a hard-coded linked list: // 2 -> 3 -> 4 -> 5 -> 6 let head = new Node(2); head.next = new Node(3); head.next.next = new Node(4); head.next.next.next = new Node(5); head.next.next.next.next = new Node(6);  console.log("Created Linked list is:"); printList(head);  // Example of appending a node  // at the end head = append(head, 1);  console.log("\nAfter inserting 1 at the end:"); printList(head); 

Output
Created Linked list is:  2 3 4 5 6 After inserting 1 at the end:  2 3 4 5 6 1

Time Complexity: O(N) where N is the length of the linked list
Auxiliary Space: O(1)


Next Article
Insert a Node at the end of Doubly Linked List

A

animeshdey
Improve
Article Tags :
  • Data Structures
  • DSA
Practice Tags :
  • Data Structures

Similar Reads

  • Insert a Node at the end of Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node at the end of the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4 Input: Linked List = NULL, NewNode = 1Output: Linked List = 1 Approach: Inserti
    9 min read
  • Insert a Node after a given Node in Linked List
    Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found". Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2Output: LinkedList = 2 -> 1 -> 3 -> 4 ->
    11 min read
  • Insert a Node at Front/Beginning of a Linked List
    Given a linked list, the task is to insert a new node at the beginning/start/front of the linked list. Example: Input: LinkedList = 2->3->4->5, NewNode = 1Output: 1 2 3 4 5 Input: LinkedList = 2->10, NewNode = 1Output: 1 2 10 Approach: To insert a new node at the front, we create a new n
    8 min read
  • Insert a node in Linked List before a given node
    Given a linked list, the task is to insert a new node with a specified value into a linked list before a node with a given key. Examples Input: head: 1 -> 2 -> 3 -> 4 -> 5 , newData = 6, key = 2Output: 1 -> 6 -> 2 -> 3 -> 4 -> 5 Explanation: After inserting node with value
    15+ min read
  • Print nodes of linked list at given indexes
    Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
    15+ min read
  • Deletion at end (Removal of last node) in a Linked List
    Given a linked list, the task is to delete the last node of the given linked list. Examples:   Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 3 -> 12 -> 15-> NULLOutp
    8 min read
  • Find extra node in the second Linked list
    Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
    7 min read
  • Insert a node at a specific position in a linked list
    Given a singly linked list, a position pos, and data, the task is to insert that data into a linked list at the given position. Examples: Input: 3->5->8->10, data = 2, pos = 2Output: 3->2->5->8->10 Input: 3->5->8->10, data = 11, pos = 5Output: 3->5->8->10->1
    8 min read
  • Delete alternate nodes of a Linked List
    Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
    14 min read
  • Insert a Node after a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2.
    11 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