
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements