Insert node at beginning of doubly linked list in swift

Swift program for Insert node at beginning of doubly linked list. Here problem description and explanation.

import Foundation
// Swift 4 Program For
// insert new node at beginning of doubly linked list

// Define class of linked list Node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	var prev: LinkNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
		self.prev = nil;
	}
}
class DoublyLinkedList
{
	var head: LinkNode? ;
	init()
	{
		self.head = nil;
	}
	// Insert new node at beginning position
	func insert(_ value: Int)
	{
		// Create a node
		let node: LinkNode? = LinkNode(value);
		node!.next = self.head;
		// When linked list is not empty
		if (self.head  != nil)
		{
			self.head!.prev = node;
		}
		// Make new head
		self.head = node;
	}
	// Display node element of doubly linked list
	func display()
	{
		if (self.head == nil)
		{
			print("Empty Linked List");
		}
		else
		{
			print("Doubly Linked List Element :");
			// Get first node of linked list
			var temp: LinkNode? = self.head;
			// iterate linked list 
			while (temp  != nil)
			{
				// Display node value
				print(temp!.data, terminator: "  ");
				// Visit to next node
				temp = temp!.next;
			}
		}
	}
	static func main(_ args: [String])
	{
		let dll: DoublyLinkedList? = DoublyLinkedList();
		// Insert following linked list nodes
		dll!.insert(70);
		dll!.insert(60);
		dll!.insert(50);
		dll!.insert(40);
		dll!.insert(30);
		dll!.insert(20);
		dll!.insert(10);
		//  NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
		dll!.display();
	}
}
DoublyLinkedList.main([String]());

Output

Doubly Linked List Element :
10  20  30  40  50  60  70


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