Reversal order of linked list using recursion in swift
Swift program for Reversal order of linked list using recursion. Here problem description and other solutions.
import Foundation
// Swift 4 program for
// Print reverse of a linked list without actually reversing
// 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 end of linked list
func addNode(_ data: Int)
{
let node: LinkNode? = LinkNode(data);
if (self.head == nil)
{
self.head = node;
}
else
{
// Append the node at last position
self.tail!.next = node;
}
self.tail = node;
}
// Display reversal view of linked list using recursion
func printReverse(_ node: LinkNode? )
{
if (node == nil)
{
return;
}
// Visit to next node
self.printReverse(node!.next);
// Display node value
print(" "
+ String(node!.data), terminator: "");
}
static func main()
{
let sll: SingleLL = SingleLL();
// 1 → 2 → 8 → 4 → 9 → 6 → NULL
sll.addNode(1);
sll.addNode(2);
sll.addNode(8);
sll.addNode(4);
sll.addNode(9);
sll.addNode(6);
// Reversal view
// 6 9 4 8 2 1
sll.printReverse(sll.head);
}
}
SingleLL.main();
Output
6 9 4 8 2 1
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