Skip to main content

Find second last element of linked list in swift

Swift program for Find second last element of linked list. Here more information.

import Foundation
// Swift 4 program for
// Find the second last node of a linked list

// Node of Linked List
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int)
	{
		// Set node value
		self.data = data;
		self.next = nil;
	}
}
class SingleLL
{
	var head: LinkNode? ;
	var tail: LinkNode? ;
	init()
	{
		self.head = nil;
		self.tail = nil;
	}
	// Add new node at the end of linked list
	func insert(_ value: Int)
	{
		// Create a new node
		let node: LinkNode? = LinkNode(value);
		if (self.head == nil)
		{
			self.head = node;
		}
		else
		{
			self.tail!.next = node;
		}
		self.tail = node;
	}
	// Display linked list element
	func display()
	{
		if (self.head == nil)
		{
			return;
		}
		var temp: LinkNode? = self.head;
		// iterating linked list elements
		while (temp  != nil)
		{
			print(String(temp!.data) + " → ", terminator: "");
			// Visit to next node
			temp = temp!.next;
		}
		print("null");
	}
	//Find the second last node of a linked list
	func secondLast()
	{
		var node: LinkNode? = self.head;
		if (node == nil)
		{
			print("Empty linked list");
		}
		else if (node!.next == nil)
		{
			print("Only one node in this linked list\n");
		}
		else
		{
			// Find second last node
			while (node!.next  != nil && 
                   node!.next!.next  != nil)
			{
				// Visit to second next node
				node = node!.next!.next;
			}
			print("Second last element is : ",node!.data);
		}
	}
	static func main(_ args: [String])
	{
		let sll: SingleLL? = SingleLL();
		// Add linked list node
		sll!.insert(6);
		sll!.insert(3);
		sll!.insert(2);
		sll!.insert(7);
		sll!.insert(1);
		sll!.insert(9);
		print("Linked List");
		// 6 → 3 → 2 → 7 → 1 → 9 → null
		sll!.display();
		sll!.secondLast();
	}
}
SingleLL.main([String]());

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