Skip to main content

construct a linked list from 2d list in python

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

#  Python 3 program for
#  Construct a linked list from 2D list
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
		self.down = None
	

class DoublyLinkedList :
	def __init__(self) :
		self.head = None
	
	def display(self) :
		if (self.head == None) :
			print("Empty linked list", end = "")
		else :
			front = self.head
			right = None
			while (front != None) :
				right = front
				while (right != None) :
					print(right.data , end = "  ")
					right = right.next
				
				print(end = "\n")
				#  Visit to down node
				front = front.down
			
		
	
	def insertData(self, matrix, rows, cols) :
		#  Some auxiliary variables
		levelHead = None
		root = None
		perv = None
		i = 0
		j = 0
		#  Add first row elements into result list 
		while (i < cols) :
			if (self.head == None) :
				#  Add first node
				self.head = LinkNode(matrix[0][i])
				levelHead = self.head
			else :
				#  next head
				levelHead.next = LinkNode(matrix[0][i])
				levelHead = levelHead.next
			
			i += 1
		
		#  Get first element    
		levelHead = self.head
		i = 1
		#  Add all the bottom element of each column
		while (i < rows) :
			root = None
			perv = root
			while (j < cols) :
				levelHead.down = LinkNode(matrix[i][j])
				if (root == None) :
					root = levelHead.down
					perv = root
				else :
					perv.next = levelHead.down
					perv = levelHead.down
				
				levelHead = levelHead.next
				j += 1
			
			levelHead = root
			#  reset col
			j = 0
			#  change row
			i += 1
		
	

def main() :
	dll = DoublyLinkedList()
	#  Create 2D metrix
	matrix = [
		[1, 6, 9, 2, -9],
		[2, 5, -5, 7, 1],
		[3, 4, 1, 8, 2]
	]
	rows = len(matrix)
	cols = len(matrix[0])
	dll.insertData(matrix, rows, cols)
	dll.display()

if __name__ == "__main__": main()

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.

New Comment