"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Reverse a linked list in go

Reverse a linked list in go

Published on 2024-07-31
Browse:643

Reverse a linked list in go

This is a favorite question to give to new developers. Pretty simple if you have had a decent data structures class.

Reverse a single linked list. (This is Leetcode 206)

For the implementation, I have chosen to make the linked list a generic type.

type Node[T any] struct {
    Data T
    Next *Node[T]
}

type LinkedList[T any] struct {
    Head *Node[T]
}

func (ll *LinkedList[T]) Append(data T) {
    newNode := &Node[T]{Data: data, Next: nil}

    if ll.Head == nil {
        ll.Head = newNode
        return
    }

    current := ll.Head
    for current.Next != nil {
        current = current.Next
    }
    current.Next = newNode
}

And for the reverse function, it's done with a single pass by recognizing that all we need to do is maintain a pointer to the previous node, then set a given node's 'next' to the previous.

When we reach the end, then we know the current node is the new 'head' of the list.

func (ll *LinkedList[T]) ReverseLinkedList() {
    var prev *Node[T] = nil
    var ptr *Node[T] = ll.Head
    for ptr != nil {
        var next *Node[T] = ptr.Next
        ptr.Next = prev
        prev = ptr
        if next == nil {
            ll.Head = ptr
        }
        ptr = next
    }
}

Have we missed a boundary condition? What complications are added if the list is now a doubly linked list? Let me know in the comments.

Thanks!

The code for this post and all posts in this series can be found here

Release Statement This article is reproduced at: https://dev.to/johnscode/reverse-a-linked-list-in-go-583i?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3