问题描述:
给你单链表的头节点head,请你反转链表,并返回反转后的链表。
示例:
输入:head = [1, 2, 3, 4, 5]
输出:[5, 4, 3, 2, 1]
解题思路:
遍历链表,创建新的节点指向新链表的head,同时修改新链表的head指向新的地址
package main
import (
"fmt"
)
type Node struct {
Value int
Next *Node
}
type List struct {
head *Node
size int
}
func New() *List {
return &List{
size: 0,
}
}
func (l *List) Append(v *Node) bool {
if v == nil {
return false
}
if l.size == 0 {
l.head = v
l.size += 1
return true
}
ptr := l.head
for i := 1; i < l.size; i++ {
ptr = ptr.Next
}
ptr.Next = v
l.size += 1
return true
}
func (l *List) Display() {
ptr := l.head
for i := 0; i < l.size; i++ {
fmt.Println("v[", i, "]", ptr.Value)
ptr = ptr.Next
}
}
func reversalList(r *List) *List {
newList := New()
ptr := r.head
for i := 1; i <= r.size; i++ {
if ptr != nil {
if newList.head == nil {
newList.head = &Node{
Value: ptr.Value,
}
newList.size = 1
} else {
l := &Node{
Value: ptr.Value,
Next: newList.head,
}
newList.head = l
newList.size += 1
}
}
ptr = ptr.Next
}
return newList
}
func main() {
list := New()
list.Append(&Node{Value: 1})
list.Append(&Node{Value: 2})
list.Append(&Node{Value: 3})
list.Append(&Node{Value: 4})
list.Append(&Node{Value: 5})
list.Display()
newList := reversalList(list)
newList.Display()
}