Table of Contents
In this tutorial, we are going to learn the writing python program to Find 3rd element of Linked List from last in Singly Linked List.
Python Program to find last 3rd element in Singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
"""Add element at the beginning"""
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def pushLast(self, new_data):
"""Add element at the end"""
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def findThirdFromEnd(self):
"""Find 3rd element from end using single pass (two-pointer approach)"""
first = self.head
second = self.head
# Move second pointer 3 steps ahead
for i in range(3):
if second is None:
print("Linked list has less than 3 elements.")
return
second = second.next
# Move both pointers until second reaches the end
while second:
first = first.next
second = second.next
print("3rd element from the end is:", first.data)
def __str__(self):
"""Return string representation of the list"""
result = []
temp = self.head
while temp:
result.append(str(temp.data))
temp = temp.next
return " -> ".join(result) if result else "[Empty List]"
# Main program
s = SinglyLinkedList()
print("Linked List Menu:")
print("1: Add element at the beginning")
print("2: Add element at the end")
print("3: Find 3rd element from the end")
print("4: Display the linked list")
print("0: Exit")
while True:
try:
choice = int(input("\nEnter your choice: "))
except ValueError:
print("[INVALID INPUT]: Please enter a valid number.")
continue
if choice == 0:
print("Exiting program.")
break
elif choice == 1:
data = input("Enter element to add at beginning: ")
s.push(data)
elif choice == 2:
data = input("Enter element to add at end: ")
s.pushLast(data)
elif choice == 3:
s.findThirdFromEnd()
elif choice == 4:
print("Linked list contents:")
print(s)
else:
print("[INVALID INPUT]: Please enter a valid menu option.")
Output
Linked List Menu:
1: Add element at the beginning
2: Add element at the end
3: Find 3rd element from the end
4: Display the linked list
0: Exit
Enter your choice: 1
Enter element to add at beginning: 3
Enter your choice: 1
Enter element to add at beginning: 5
Enter your choice: 1
Enter element to add at beginning: 8
Enter your choice: 2
Enter element to add at end: 9
Enter your choice: 4
Linked list contents:
8 -> 5 -> 3 -> 9
Enter your choice: 3
3rd element from the end is: 5
Enter your choice: 0
Exiting program.
What did you think?
Similar Reads
-
Find middle element of a linked list in single pass
Linked lists are a fundamental data structure used in computer science for organizing and managing data. A linked list is… -
Most important JavaScript Interview Questions To Prepare
In this Page we have collected and explained Most important Javascript Interview Questions and Answers for begineers, freshers as well… -
Sum of digits of Given Number in Java
In this tutorial we will learn writing Java program to calculate the sum of its digit. We will also see… -
Hibernate Interview Questions for 2+ years of experience
Certainly! Here's a list of commonly asked interview questions on Hibernate for candidates with 2+ years of experience: Basic Hibernate… -
68 Most Important Microservices Interview Questions
Certainly, here's an extended list of 50 commonly asked interview questions on microservices for candidates with 2+ years of experience:… -
60 Most Important Git Interview Questions
Certainly! Here is a list of commonly asked interview questions on Git for candidates with fresher or having of experience… -
50+ Most important Java Interview Questions for 5+ Years Exp
1. Explain the SOLID principles in Java. Provide examples of how you have applied these principles in your projects. SOLID… -
60+ Spring Boot interview questions for 4+ years Exp.
1. What is Spring Boot and how does it differ from the Spring framework? Spring Boot is a framework designed… -
60+ Mostly Asked Spring Boot Interview Questions for 3+ Yrs
Here is a list of 60+ Spring Boot interview questions for candidates with 3+ years of experience: 1. What is… -
Scenario Based Java 8 Coding Interview Questions (For Experienced)
Generally, most websites cover basic Java 8 coding problems, But when you appear in the interview as an experience, Interviewer…