Skip to main content

Find second last element of linked list in golang

Go program for Find second last element of linked list. Here problem description and other solutions.

package main
import "fmt"
// Go program for
// Find the second last node of a linked list

// Node of Linked List
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,
	}
}
// Add new node at the end of linked list
func(this *SingleLL) insert(value int) {
	// Create a new node
	var node * LinkNode = getLinkNode(value)
	if this.head == nil {
		this.head = node
	} else {
		this.tail.next = 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.Print("null\n")
}
//Find the second last node of a linked list
func(this SingleLL) secondLast() {
	var node * LinkNode = this.head
	if node == nil {
		fmt.Print("Empty linked list")
	} else if node.next == nil {
		fmt.Print("Only one node in this linked list")
	} else {
		// Find second last node
		for (node.next != nil && node.next.next != nil) {
			// Visit to second next node
			node = node.next.next
		}
		fmt.Println("Second last element is : ", node.data)
	}
}
func main() {
	var sll * SingleLL = getSingleLL()
	// Add linked list node
	sll.insert(6)
	sll.insert(3)
	sll.insert(2)
	sll.insert(7)
	sll.insert(1)
	sll.insert(9)
	fmt.Println("Linked List")
	// 6 → 3 → 2 → 7 → 1 → 9 → null
	sll.display()
	sll.secondLast()
}

Output

Linked List6 → 3 → 2 → 7 → 1 → 9 → null
Second last element is : 1




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