Skip to main content

Find the smallest number in the doubly linked list in golang

Go program for Find the smallest number in the doubly linked list. Here more information.

package main
import "fmt"
// Go program for
// Find the smallest node in doubly linked list

// Linked List Node
type LinkNode struct {
	data int
	next * LinkNode
	prev * LinkNode
}
func getLinkNode(data int) * LinkNode {
	// return new LinkNode
	return &LinkNode {
		data,
		nil,
		nil,
	}
}
type DoublyLinkedList struct {
	head * LinkNode
	tail * LinkNode
}
func getDoublyLinkedList() * DoublyLinkedList {
	// return new DoublyLinkedList
	return &DoublyLinkedList {
		nil,
		nil,
	}
}
// Insert new node at end position
func(this *DoublyLinkedList) insert(value int) {
	// Create a node
	var node * LinkNode = getLinkNode(value)
	if this.head == nil {
		// Add first node
		this.head = node
		this.tail = node
		return
	}
	// Add node at last position
	this.tail.next = node
	node.prev = this.tail
	// new last node
	this.tail = node
}
// Find smallest number
func(this DoublyLinkedList) minNumber() {
	if this.head == nil {
		fmt.Println("Empty Linked List")
	} else {
		// Get first node of linked list
		var temp * LinkNode = this.head
		var result int = temp.data
		// iterate linked list 
		for (temp != nil) {
			if temp.data < result {
				// Get new minimum
				result = temp.data
			}
			// Visit to next node
			temp = temp.next
		}
		fmt.Println("Smallest : ", result)
	}
}
func main() {
	var dll * DoublyLinkedList = getDoublyLinkedList()
	// Insert following linked list nodes
	dll.insert(14)
	dll.insert(31)
	dll.insert(12)
	dll.insert(15)
	dll.insert(11)
	dll.insert(25)
	dll.minNumber()
}

Output

Smallest : 11




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