Posted on by Kalkicode
Code Single linked list

Find second last element in linked list in c++

C++ program for Find second last element in linked list. Here more information.

// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Find the second last node of a linked list

// Node of Linked List
class LinkNode
{
	public: 
    int data;
	LinkNode *next;
	LinkNode(int data)
	{
		// Set node value
		this->data = data;
		this->next = nullptr;
	}
};
class SingleLL
{
	public: LinkNode *head;
	LinkNode *tail;
	SingleLL()
	{
		this->head = nullptr;
		this->tail = nullptr;
	}
	// Add new node at the end of linked list
	void insert(int value)
	{
		// Create a new node
		LinkNode *node = new LinkNode(value);
		if (this->head == nullptr)
		{
			this->head = node;
		}
		else
		{
			this->tail->next = node;
		}
		this->tail = node;
	}
	// Display linked list element
	void display()
	{
		if (this->head == nullptr)
		{
			return;
		}
		LinkNode *temp = this->head;
		// iterating linked list elements
		while (temp != nullptr)
		{
			cout << temp->data << " → ";
			// Visit to next node
			temp = temp->next;
		}
		cout << "null\n";
	}
	//Find the second last node of a linked list
	void secondLast()
	{
		LinkNode *node = this->head;
		if (node == nullptr)
		{
			cout << "Empty linked list";
		}
		else if (node->next == nullptr)
		{
			cout << "Only one node in this linked list";
		}
		else
		{
			// Find second last node
			while (node->next != nullptr && node->next->next != nullptr)
			{
				// Visit to second next node
				node = node->next->next;
			}
			cout << "Second last element is : " << node->data << endl;
		}
	}
};
int main()
{
	SingleLL *sll = new SingleLL();
	// Add linked list node
	sll->insert(6);
	sll->insert(3);
	sll->insert(2);
	sll->insert(7);
	sll->insert(1);
	sll->insert(9);
	cout << "Linked List" << endl;
	// 6 → 3 → 2 → 7 → 1 → 9 → null
	sll->display();
	sll->secondLast();
	return 0;
}

Output

Linked List
6 → 3 → 2 → 7 → 1 → 9 → null
Second last element is : 1

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment