Form a Rectangle from boundary elements of Matrix using Linked List | Javascript program for above approach Node Class ; Constructor to initialize the node object ; Linked List class ; Constructor to initialize head ; function to form square linked list of matrix . ; initialising A [ 0 ] [ 0 ] as head . ; head is assigned to head . ; i is row index , j is column index ; loop till temp . top become equal to head . ; iterating over first i . e 0 th row and connecting node . ; iterating over last i . e ( m - 1 ) th column and connecting Node . ; iterating over last i . e ( n - 1 ) th row and connecting Node . ; iterating over first i . e 0 th column and connecting Node . ; function to print Linked list . ; printing head of linked list ; loop till temp . top become equal to head ; printing the node ; Driver Code ; n is number of rows ; m is number of column ; creation of object ; Call Quad method to create Linked List . ; Call printList method to print list .
class Node { constructor ( val ) { this . data = val this . next = null this . prev = null this . top = null this . bottom = null } } class LinkedList { constructor ( ) { this . head = null } Quad ( grid , n , m ) { this . head = new Node ( grid [ 0 ] [ 0 ] ) let temp = this . head let i = 0 let j = 1 while ( temp . top != this . head ) { if ( j < m && i == 0 ) { temp . next = new Node ( grid [ i ] [ j ] ) temp = temp . next j += 1 } else if ( j == m && i < n - 1 ) { i = i + 1 temp . bottom = new Node ( grid [ i ] [ j - 1 ] ) temp = temp . bottom } else if ( i == n - 1 && j <= m && j >= 1 ) { if ( j == m ) j = j - 1 j = j - 1 temp . prev = new Node ( grid [ i ] [ j ] ) temp = temp . prev } else if ( i <= n - 1 && j == 0 ) { i = i - 1 temp . top = new Node ( grid [ i ] [ j ] ) temp = temp . top if ( i == 1 ) temp . top = this . head } } } printList ( root ) { let temp = root document . write ( temp . data + " " ) while ( temp . top != root ) { if ( temp . next ) { document . write ( temp . next . data + " " ) temp = temp . next } if ( temp . prev ) { document . write ( temp . prev . data + " " ) temp = temp . prev } if ( temp . bottom ) { document . write ( temp . bottom . data + " " ) temp = temp . bottom } if ( temp . top ) { document . write ( temp . top . data + " " ) temp = temp . top } } } } let grid = [ [ 13 , 42 , 93 , 88 ] , [ 26 , 38 , 66 , 42 ] , [ 75 , 63 , 78 , 12 ] ] let n = grid . length let m = grid [ 0 ] . length let l = new LinkedList ( ) l . Quad ( grid , n , m ) l . printList ( l . head )