Posted on by Kalkicode
Code Single linked list

Sort absolute sorted linked list in golang

Go program for Sort absolute sorted linked list. Here more information.

package main
import "fmt"
// Go program for
// Sort linked list which is already 
// sorted on absolute values

// 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
}
func getSingleLL() * SingleLL {
	// return new SingleLL
	return &SingleLL {
		nil,
	}
}
// Add new node at the end of linked list
func(this *SingleLL) insert(value int) {
	// Create a node
	var node * LinkNode = getLinkNode(value)
	if this.head == nil {
		this.head = node
	} else {
		var temp * LinkNode = this.head
		// Find last node
		for (temp.next != nil) {
			// Visit to next node
			temp = temp.next
		}
		// Add node at last position
		temp.next = node
	}
}
// Display all Linked List elements
func(this SingleLL) display() {
	if this.head != nil {
		fmt.Println("Linked list")
		var temp * LinkNode = this.head
		for (temp != nil) {
			// Display node value
			fmt.Print("  ", temp.data)
			// Visit to next node
			temp = temp.next
		}
	} else {
		fmt.Println("Empty Linked list")
	}
}
func(this *SingleLL) sort() {
	if this.head == nil {
		fmt.Println("Empty linked list")
	} else {
		var current * LinkNode = this.head
		var temp * LinkNode = nil
		for (current != nil && current.next != nil) {
			if current.data > current.next.data {
				// Move node at the beginning
				temp = current.next.next
				current.next.next = this.head
				// Set new head
				this.head = current.next
				current.next = temp
			} else {
				// Visit to next node
				current = current.next
			}
		}
	}
}
func main() {
	var sll * SingleLL = getSingleLL()
	// Linked list sll1
	// 0 → 5 → -5 → 6 → -7 → 8 → 9 → -10 → NULL
	sll.insert(0)
	sll.insert(5)
	sll.insert(-5)
	sll.insert(6)
	sll.insert(-7)
	sll.insert(8)
	sll.insert(9)
	sll.insert(-10)
	fmt.Println("Before sort")
	// Display all node
	sll.display()
	sll.sort()
	fmt.Println("\nAfter sort")
	// Display all node
	sll.display()
}

Output

Before sort
Linked list
  0  5  -5  6  -7  8  9  -10
After sort
Linked list
  -10  -7  -5  0  5  6  8  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