Skip to main content

Subtraction of alternate nodes of linked list in golang

Go program for Subtraction of alternate nodes of linked list. Here problem description and other solutions.

package main
import "fmt"
/*
    Go program for
    Subtraction of the alternate nodes of linked list
*/
// Linked list node
type LinkNode struct {
	data int
	next * LinkNode
}
func getLinkNode(data int) * LinkNode {
	// return new LinkNode
	return &LinkNode {
		data,
		nil,
	}
}
type SingleLL struct {
	head * LinkNode
	tail * LinkNode
}
func getSingleLL() * SingleLL {
	// return new SingleLL
	return &SingleLL {
		nil,
		nil,
	}
}
func(this *SingleLL) insert(data int) {
	var node * LinkNode = getLinkNode(data)
	if this.head == nil {
		// Add first node
		this.head = node
	} else {
		// Add node at the end position
		this.tail.next = node
	}
	// New last node
	this.tail = node
}
// Display linked list element
func(this SingleLL) display() {
	if this.head == nil {
		return
	}
	var temp * LinkNode = this.head
	// iterating linked list elements
	for (temp != nil) {
		fmt.Print(" ", temp.data, " →")
		// Visit to next node
		temp = temp.next
	}
	fmt.Println(" NULL")
}
// Find the subtraction of all alternate 
// nodes in linked list
func(this SingleLL) alternateSubtraction() {
	// Define resultant variables
	var result int = 0
	var counter int = 0
	// Start to first node of linked list
	var temp * LinkNode = this.head
	// iterating linked list elements
	for (temp != nil) {
		if counter % 2 == 0 {
			// When get alternate node
			if result == 0 {
				result = temp.data
			} else {
				result = result - temp.data
			}
		}
		// Node counter
		counter++
		// Visit to next node
		temp = temp.next
	}
	fmt.Println(" Alternate nodes subtraction : ", result)
}
func main() {
	var sll * SingleLL = getSingleLL()
	// Add node in linked list
	// 4 → 7 → 2 → 9 → 1 → 3 → 4 → 3 → 6 → NULL
	sll.insert(4)
	sll.insert(7)
	sll.insert(2)
	sll.insert(9)
	sll.insert(1)
	sll.insert(3)
	sll.insert(4)
	sll.insert(3)
	sll.insert(6)
	// Display of linked list nodes
	sll.display()
	// Test
	sll.alternateSubtraction()
}

Output

 4 → 7 → 2 → 9 → 1 → 3 → 4 → 3 → 6 → NULL
 Alternate nodes subtraction : -9




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