# Form a Rectangle from boundary elements of Matrix using Linked List

class Node: def __init__(self, val): self.data = val self.next = None self.prev = None self.top = None self.bottom = None class LinkedList: def __init__(self): self.head = None def Quad(self, grid, n, m): self.head = Node(grid[0][0]) temp = self.head i = 0 j = 1 while temp.top != self.head: if j < m and i == 0: temp.next = Node(grid[i][j]) temp = temp.next j += 1 elif j == m and i < n - 1: i = i + 1 temp.bottom = Node(grid[i][j - 1]) temp = temp.bottom elif i == n - 1 and j = 1: if j == m: j = j - 1 j = j - 1 temp.prev = Node(grid[i][j]) temp = temp.prev elif i