遍历链表
Created on 03 Nov 2026 at 00:00
数据结构
//比如 1,1,0 转换为10进制数
//初始化为 0。
//0*2 + 1 = 1
//1*2 + 1 = 3
//3*2 + 0 = 6
二进制110转换为十进制就为6
package main
import "fmt"
//链表
type ListNode struct {
Val int
Next *ListNode
}
func GetDecimalValue(head *ListNode) int {
ans := 0
for head != nil {
ans = ans*2 + head.Val
head = head.Next
}
return ans
}
func main() {
// Example usage
node1 := &ListNode{Val: 1}
node2 := &ListNode{Val: 0}
node3 := &ListNode{Val: 1}
node1.Next = node2
node2.Next = node3
fmt.Println(GetDecimalValue(node1)) // Output: 5
}