Insert linked list node at nth last position in swift

Swift program for Insert linked list node at nth last position. Here problem description and explanation.

import Foundation
// Swift 4 program for
// Insert linked list node at nth last position 

// Linked list node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
	}
}
class LinkedList
{
	var head: LinkNode? ;
	init()
	{
		self.head = nil;
	}
	// insert node at end position
	func insert(_ value: Int)
	{
		// Create a new node
		let node: LinkNode? = LinkNode(value);
		if (self.head == nil)
		{
			self.head = node;
		}
		else
		{
			var temp: LinkNode? = self.head;
			// Find the last node
			while (temp!.next  != nil)
			{
				// Visit to next node
				temp = temp!.next;
			}
			// Add node
			temp!.next = 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(temp!.data, terminator: " → ");
			// Visit to next node
			temp = temp!.next;
		}
		print("NULL");
	}
	// Add node at specific position from the end of linked list
	func endPosition(_ n: Int, _ value: Int)
	{
		if (self.head == nil)
		{
			print("Empty Linked list");
		}
		else if (n <= 0)
		{
			print("Invalid position");
		}
		else
		{
			var temp: LinkNode? = self.head;
			var location: LinkNode? = nil;
            var position  = n;
			while (temp  != nil)
			{
				position -= 1;
				if (position <= 0)
				{
					if (location == nil)
					{
						location = self.head;
					}
					else
					{
						location = location!.next;
					}
				}
				// visit to next node
				temp = temp!.next;
			}
			if (position <= 1)
			{
				let node: LinkNode? = LinkNode(value);
				if (location == nil)
				{
					// Add node at first place
					node!.next = self.head;
					self.head = node;
				}
				else
				{
					// Add node at intermediate position
					node!.next = location!.next;
					location!.next = node;
				}
			}
			else
			{
				print("Opps position not found");
			}
		}
	}
	static func main(_ args: [String])
	{
		let sll: LinkedList? = LinkedList();
		// Add node
		sll!.insert(5);
		sll!.insert(4);
		sll!.insert(3);
		sll!.insert(2);
		sll!.insert(1);
		sll!.display();
		let position: Int = 2;
		let data: Int = 10;
		sll!.endPosition(position, data);
		print(" Add "
			+ String(data) + " at last "
			+ String(position) + "-nd position");
		sll!.display();
	}
}
LinkedList.main([String]());

Output

5 → 4 → 3 → 2 → 1 → NULL
 Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → 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