面試演算法,談到連結串列,一般會考察連結串列的反轉
思路:修改每個節點的next指標即可。建立三個變數
current:當前處理的節點
pre:當前處理的節點的前驅節點,需要賦值給current.next實現反轉
nextNode:下一個要處理的節點
package main
import "fmt"
type Node struct{
data int
next *Node
}
type List struct {
Head *Node
len int
}
func NewNode(data int)*Node{
return &Node{data:data,next:nil}
}
func NewList()*List{
return &List{nil,0}
}
func (l *List)Push(data int){
newNode := NewNode(data)
current := l.Head
if current == nil {
l.Head = newNode
return
}
for current.next != nil {
current = current.next
}
current.next = newNode
}
func print(l *List){
node := l.Head
for node != nil{
fmt.Println(node.data)
node = node.next
}
}
func main(){
l := NewList()
l.Push(3)
l.Push(6)
l.Push(1)
print(l)
reverseList(l)
print(l)
}
//單連結串列反轉,對每個節點一一修改
func reverseList(l *List){
current := l.Head
var pre *Node
for current != nil{
nextNode := current.next //記錄下一個修改的節點
current.next = pre//當前節點的next就是pre
pre = current //當前節點就是下一個節點的pre
current = nextNode
}
l.Head = pre
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結