

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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.
- Find the Second Largest Element in a Linked List in C++
- Python Program to Print Nth Node from the last of a Linked List
- Find modular node in a linked list in C++
- C# Program to add a node at the last position in a Linked List
- Find the largest node in Doubly linked list in C++
- Program to find the middle node of a singly linked list in Python
- C# program to find node in Linked List
- Finding middlemost node of a linked list in JavaScript
- Delete Node in a Linked List in Python
- Find the product of last N nodes of the given Linked List in C++
- Find kth node from Middle towards Head of a Linked List in C++
Advertisements