Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Reverse a linked list in Go (Golang)

Posted on August 21, 2023August 21, 2023 by admin

Table of Contents

  • Overview
  • Program

Overview

The objective is to reverse a given linked list.

Eg

Input: 3->2->1
Output: 1->2->3

Program

Below is a program for the same

package main
import "fmt"
func main() {
first := initList()
first.AddFront(1)
first.AddFront(2)
first.AddFront(3)
first.AddFront(4)
first.Head.Traverse()
first.Reverse()
fmt.Println("")
first.Head.Traverse()
}
func initList() *SingleList {
return &SingleList{}
}
type ListNode struct {
Val int
Next *ListNode
}
func (l *ListNode) Traverse() {
for l != nil {
fmt.Println(l.Val)
l = l.Next
}
}
type SingleList struct {
Len int
Head *ListNode
}
func (s *SingleList) Reverse() {
curr := s.Head
var prev *ListNode
var next *ListNode
for curr != nil {
next = curr.Next
curr.Next = prev
prev = curr
curr = next
}
s.Head = prev
}
func (s *SingleList) AddFront(num int) {
ele := &ListNode{
Val: num,
}
if s.Head == nil {
s.Head = ele
} else {
ele.Next = s.Head
s.Head = ele
}
s.Len++
}

Output

4
3
2
1
1
2
3
4

Note: Check out our Golang Advanced Tutorial. The tutorials in this series are elaborative and we have tried to cover all concepts with examples. This tutorial is for those who are looking to gain expertise and a solid understanding of golang – Golang Advance Tutorial

Also if you are interested in understanding how all design patterns can be implemented in Golang. If yes, then this post is for you –All Design Patterns Golang

  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP