/*
*/
package main
import "fmt"
type node struct {
value int
next *node
}
func main() {
head := node{}
curr := &head
for i := 1; i < 10; i++ {
temp := new(node)
temp.value = i
curr.next = temp
curr = curr.next
}
cur := reverse(&head)
for {
if cur != nil {
fmt.Println(cur.value)
} else {
break
}
cur = cur.next
}
}
func reverse(head *node) *node {
pReverseHead := new(node)
pNode := head
pPre := new(node)
for pNode != nil {
pNext := pNode.next
if pNext == nil {
pReverseHead = pNode
}
pNode.next = pPre
pPre = pNode
pNode = pNext
}
return pReverseHead
}
使用三个临时变量对指针操作,无需额外内存消耗。