Delete last node of linked list in swift

Swift program for Delete last node of linked list. Here problem description and explanation.

import Foundation
/*
    Swift 4 program for
    Delete the last node of singly linked list
*/
// Linked list node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int)
	{
		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 addNode(_ value: Int)
	{
		// Create a new node
		let node: LinkNode? = LinkNode(value);
		if (self.head == nil)
		{
			self.head = node;
		}
		else
		{
			self.tail!.next = node;
		}
		// Set new last node
		self.tail = node;
	}
	// Display linked list element
	func display()
	{
		if (self.head == nil)
		{
			print("Empty Linked List");
			return;
		}
		var temp: LinkNode? = self.head;
		// iterating linked list elements
		while (temp  != nil)
		{
			print(temp!.data, terminator: " → ");
			// Visit to next node
			temp = temp!.next;
		}
		print("NULL");
	}
	// Delete last node of singly linked list
	func deleteLastNode()
	{
		if (self.head == nil)
		{
			print("Empty Linked List");
			return;
		}
		else
		{
			var temp: LinkNode? = self.head;
			var find: LinkNode? = nil;
			// Find second last node
			while (temp!.next  != nil)
			{
				find = temp;
				temp = temp!.next;
			}
			if (find == nil)
			{
				// Delete head node of linked list
				self.head = nil;
				self.tail = nil;
			}
			else
			{
				// Set new last node
				self.tail = find;
				find!.next = nil;
			}
		}
	}
	static func main(_ args: [String])
	{
		let sll: SingleLL? = SingleLL();
		// Linked list
		// 1 → 2 → 3 → 4 → 5 → 6 → NULL
		sll!.addNode(1);
		sll!.addNode(2);
		sll!.addNode(3);
		sll!.addNode(4);
		sll!.addNode(5);
		sll!.addNode(6);
		print("Before Delete ");
		sll!.display();
		sll!.deleteLastNode();
		print("After Delete ");
		sll!.display();
	}
}
SingleLL.main([String]());

Output

Before Delete
1 → 2 → 3 → 4 → 5 → 6 → NULL
After Delete
1 → 2 → 3 → 4 → 5 → NULL


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







© 2021, kalkicode.com, All rights reserved