Golang递归实现链表反转

反转前的链表:A->B->C->D->E->F->G->H->I->J->K->L->M->N->O->P->Q->R->S->T->U->V->W->X->Y->Z
反转后的链表:Z->Y->X->W->V->U->T->S->R->Q->P->O->N->M->L->K->J->I->H->G->F->E->D->C->B->A

package main

import "fmt"

type List struct {
    value string
    next *List
}
func main(){
    // 头指针
    var head *List
    // 尾指针
    var last *List
    for i := 'A'; i < 'Z'+1; i++{
        // 记录尾部的指针
        last = GenerateList(last, string(i))
        if head == nil {
            // 记录头部指针
            head = last
        }
    }
    fmt.Print("反转前的链表:")
    show(head)
    Recursion(head)
    fmt.Print("反转后的链表:")
    show(last)
    fmt.Println("
")
}
// 递归反转
func Recursion(l *List, parme ...int) *List{
    // 第一次调用,不能传参
    if len(parme) == 0{
        parme = []int{0}
    }
    // 节点不存在返回空,也就是最后一个节点的next值
    if l == nil {
        return nil
    }
    // 通过递归,获取到下一个节点的值
    next := Recursion(l.next, parme[0]+1)
    // 最后一个则返回当前节点
    if next == nil{
        return l
    }
    // 反转接,将下一个节点指向上一个节点
    next.next = l
    if parme[0] == 0 {
        l.next = nil

    }
    // 返回当前节点
    return l
}
// 生成链表值
func GenerateList(l *List, value string) *List{
    // 头链表直接返回
    if l == nil {
        return &List{value: value}
    }
    l.next = &List{value: value}
    return l.next
}
// 显示链表的值
func show(l *List){
    for l != nil {
        fmt.Print(l.value)
        if l.next != nil {
            fmt.Print("->")
        }
        l = l.next
    }
    fmt.Println()
}
原文地址:https://www.cnblogs.com/hardykay/p/14595069.html