Posted on by Kalkicode

# construct a linked list from 2d matrix in swift

Swift program for construct a linked list from 2d matrix. Here problem description and other solutions.

``````import Foundation
// Swift 4 program for
// Construct a linked list from 2D matrix
{
var data: Int;
init(_ data: Int)
{
self.data = data;
self.next = nil;
self.down = nil;
}
}
{
init()
{
}
func display()
{
{
}
else
{
while (front  != nil)
{
right = front;
while (right  != nil)
{
print(right!.data, terminator:  "  ");
right = right!.next;
}
print();
// Visit to down node
front = front!.down;
}
}
}
func insertData(_ matrix: [
[Int]
], _ rows: Int, _ cols: Int)
{
// Some auxiliary variables
var i: Int = 0;
var j: Int = 0;
// Add first row elements into result list
while (i < cols)
{
{
}
else
{
}
i += 1;
}
// Get first element
i = 1;
// Add all the bottom element of each column
while (i < rows)
{
root = nil;
perv = root;
while (j < cols)
{
if (root == nil)
{
perv = root;
}
else
{
}
j += 1;
}
// reset col
j = 0;
// change row
i += 1;
}
}
static func main(_ args: [String])
{
// Create 2D metrix
let matrix: [
[Int]
] = [
[1, 6, 9, 2, -9],
[2, 5, -5, 7, 1],
[3, 4, 1, 8, 2]
];
let rows: Int = matrix.count;
let cols: Int = matrix[0].count;
dll.insertData(matrix, rows, cols);
dll.display();
}
}

Output

``````1  6  9  2  -9
2  5  -5  7  1
3  4  1  8  2``````

## Comment

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.

Categories
Relative Post