
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the second last node of a linked list in single traversal in C++
Now we will see how to get the second last element in the linked list. Suppose there are few elements like [10, 52, 41, 32, 69, 58, 41], second last element is 58.
To solve this problem, we will use two pointers one will point to current node, and another will point to previous node of the current position, then we will move until the next of current is null, then simply return the previous node.
Example
#include<iostream> using namespace std; class Node { public: int data; Node *next; }; void prepend(Node** start, int new_data) { Node* new_node = new Node; new_node->data = new_data; new_node->next = NULL; if ((*start) != NULL){ new_node->next = (*start); *start = new_node; } (*start) = new_node; } int secondLastElement(Node *start) { Node *curr = start, *prev = NULL; while(curr->next != NULL){ prev = curr; curr = curr->next; } return prev->data; } int main() { Node* start = NULL; prepend(&start, 15); prepend(&start, 20); prepend(&start, 10); prepend(&start, 9); prepend(&start, 7); prepend(&start, 17); cout << "Second last element is: " << secondLastElement(start); }
Output
Second last element is: 20
- Related Articles
- Program to find the K-th last node of a linked list in Python
- Remove Last Node of the Linked List using C++
- Golang Program to update the last node value in a linked list.
- Golang Program to delete the last node from a linked list.
- C# Program to add a node at the last position in a Linked List
- Find modular node in a linked list in C++
- Python Program to Print Nth Node from the last of a Linked List
- Find the Second Largest Element in a Linked List in C++
- Find the largest node in Doubly linked list in C++
- C# program to find node in Linked List
- Program to find the middle node of a singly linked list in Python
- Delete Node in a Linked List in Python
- Finding middlemost node of a linked list in JavaScript
- Linked List Random Node in C++
- Find kth node from Middle towards Head of a Linked List in C++

Advertisements