Remove duplicates from unsorted linked list in swift

Swift program for Remove duplicates from unsorted linked list. Here problem description and explanation.

import Foundation
// Swift 4 Program to 
// Delete duplicate nodes in unsorted linked list
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
	}
}
class LinkedList
{
	var head: LinkNode? ;
	var tail: LinkNode? ;
	// Class constructors
	init()
	{
		self.head = nil;
		self.tail = nil;
	}
	// Insert new element at end position
	func insert(_ value: Int)
	{
		// Create new node
		let node: LinkNode? = LinkNode(value);
		if (self.head == nil)
		{
			// Add first node
			self.head = node;
		}
		else
		{
			// Add new node at the last position
			self.tail!.next = node;
		}
		// Make new tail 
		self.tail = node;
	}
	// Display all node value
	func display()
	{
		if (self.head  != nil)
		{
			print("Linked List Element : ", terminator: "");
			var temp: LinkNode? = self.head;
			while (temp  != nil)
			{
				// Display node value
				print(temp!.data, terminator: "  ");
				// Visit to next node
				temp = temp!.next;
			}
		}
		else
		{
			print("Empty Linked list");
		}
	}
	func removeNode()
	{
		if (self.head == nil)
		{
			// When linked list empty
			print("Empty Linked list");
		}
		else
		{
			// Auxiliary variable
			var temp: LinkNode? = self.head;
			var hold: LinkNode? = nil;
			var initial: LinkNode? = nil;
			var current: LinkNode? = nil;
			// Outer loop
			while (temp  != nil)
			{
				// New last node
				self.tail = temp;
				current = temp;
				initial = current!.next;
				// Inner loop
				// Remove all node which value is similar to temp node
				while (initial  != nil)
				{
					if (temp!.data == initial!.data)
					{
						// Get remove node
						hold = initial;
					}
					else
					{
						current = initial;
					}
					// Visit to next node
					initial = initial!.next;
					if (hold  != nil)
					{
						current!.next = initial;
						// remove node
						hold = nil;
					}
				}
				// Visit to next node
				temp = temp!.next;
			}
		}
	}
	static func main(_ args: [String])
	{
		// new linked list
		let task: LinkedList? = LinkedList();
		// Add tested element
		task!.insert(1);
		task!.insert(2);
		task!.insert(9);
		task!.insert(4);
		task!.insert(9);
		task!.insert(3);
		task!.insert(1);
		task!.insert(7);
		task!.insert(2);
		task!.insert(1);
		print("\nBefore Delete ");
		task!.display();
		task!.removeNode();
		print("\nAfter Delete ");
		task!.display();
	}
}
LinkedList.main([String]());

Output

Before Delete
Linked List Element : 1  2  9  4  9  3  1  7  2  1
After Delete
Linked List Element : 1  2  9  4  3  7



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







© 2022, kalkicode.com, All rights reserved