Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to reverse a singly linked list in-place in Go

1 Answer

0 votes
package main

import "fmt"

// ListNode represents a node in a singly linked list.
type ListNode struct {
    value int        // data stored in the node
    next  *ListNode  // pointer to the next node
}

// reverseList reverses a singly linked list in-place.
func reverseList(head *ListNode) *ListNode {
    var prev *ListNode = nil      // will become the new head
    current := head               // pointer to traverse the list

    for current != nil {
        nextNode := current.next  // save next node
        current.next = prev       // reverse the link
        prev = current            // move prev forward
        current = nextNode        // move current forward
    }

    return prev // prev is the new head
}

// printList prints the linked list in a readable format.
func printList(head *ListNode) {
    for temp := head; temp != nil; temp = temp.next {
        fmt.Print(temp.value)
        if temp.next != nil {
            fmt.Print(" -> ")
        }
    }
    fmt.Println()
}

func main() {
    // Build a sample list: 1 -> 2 -> 3 -> 4 -> 5
    head := &ListNode{value: 1}
    head.next = &ListNode{value: 2}
    head.next.next = &ListNode{value: 3}
    head.next.next.next = &ListNode{value: 4}
    head.next.next.next.next = &ListNode{value: 5}

    fmt.Println("Original list:")
    printList(head)

    // Reverse the list
    head = reverseList(head)

    fmt.Println("Reversed list:")
    printList(head)
}



/*
run:

Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1

*/

 



answered Jun 30 by avibootz
...