反转链表go语言手撕(Goland上编写)

在Goland上手写反转链表,并且写出例子运行一下。好久没写力扣,有点手生了,面试官说,如果我好久没写这个,就最好不要在简历上写,他说他是希望我能够手撕算法的。

算是积累经验了。。

package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func reverseList(head *ListNode) *ListNode {
	var before *ListNode
	var now *ListNode
	now = head
	for now != nil {
		next := now.Next
		now.Next = before
		before = now
		now = next
	}
	return before
}

func printList(head *ListNode) {
	cur := head
	for cur != nil {
		fmt.Printf("%d ", cur.Val)
		cur = cur.Next
	}
	fmt.Println("")
}

func main() {
	a := &ListNode{Val: 1}
	b := &ListNode{Val: 2}
	c := &ListNode{Val: 3}
	d := &ListNode{Val: 4}
	e := &ListNode{Val: 5}
	a.Next = b
	b.Next = c
	c.Next = d
	d.Next = e
	e.Next = nil
	printList(a)

	x := reverseList(a)
	printList(x)

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,由于go语言的正确写法是"golang",我可以为您提供一个golang语言编写的简单区块链代码示例: ```go package main import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "time" ) // 区块结构体 type Block struct { Index int // 区块索引 Timestamp string // 时间戳 Data string // 区块数据 PrevHash string // 上一个区块的哈希值 Hash string // 当前区块的哈希值 } // 计算哈希值 func calculateHash(block Block) string { record := fmt.Sprintf("%d%s%s%s", block.Index, block.Timestamp, block.Data, block.PrevHash) h := sha256.New() h.Write([]byte(record)) hashed := h.Sum(nil) return hex.EncodeToString(hashed) } // 生成新区块 func generateBlock(prevBlock Block, data string) Block { var newBlock Block newBlock.Index = prevBlock.Index + 1 newBlock.Timestamp = time.Now().String() newBlock.Data = data newBlock.PrevHash = prevBlock.Hash newBlock.Hash = calculateHash(newBlock) return newBlock } // 验证区块是否合法 func isBlockValid(newBlock, prevBlock Block) bool { if prevBlock.Index+1 != newBlock.Index { return false } if prevBlock.Hash != newBlock.PrevHash { return false } if calculateHash(newBlock) != newBlock.Hash { return false } return true } // 区块链结构体 type Blockchain struct { Chain []Block // 区块链 } // 添加新区块 func (bc *Blockchain) AddBlock(data string) { prevBlock := bc.Chain[len(bc.Chain)-1] newBlock := generateBlock(prevBlock, data) if isBlockValid(newBlock, prevBlock) { bc.Chain = append(bc.Chain, newBlock) } } // 初始化区块链 func initializeBlockchain() Blockchain { return Blockchain{[]Block{{ Index: 0, Timestamp: time.Now().String(), Data: "Genesis Block", PrevHash: "", Hash: "", }}} } // 打印区块链 func printBlockchain(bc Blockchain) { bcJson, _ := json.MarshalIndent(bc, "", " ") fmt.Println(string(bcJson)) } func main() { bc := initializeBlockchain() bc.AddBlock("Block 1") bc.AddBlock("Block 2") printBlockchain(bc) } ``` 这是一个非常简单的区块链代码,它实现了区块的创建、校验和链的打印功能。当然,在实际应用中,需要考虑更多的安全和性能问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值