package main
import (
"fmt"
"log"
)
type Node struct {
Value int
Next *Node
}
func (node *Node) Print() {
head := node
for head != nil {
fmt.Printf("%d ", head.Value)
head = head.Next
}
fmt.Println()
}
func main() {
m := 50
n := 10
head1 := makeList(m)
head1.Print()
head2 := makeList(n)
head2.Print()
checkSameNode(head1, head2, m, n)
}
func checkSameNode(head1, head2 *Node, m int, n int) {
var node *Node
if m == n {
node = findSameNode(head1, head2)
} else {
h1, h2 := alignLists(head1, head2, m, n)
node = findSameNode(h1, h2)
}
if node != nil {
log.Printf("Find same node: %d", node.Value)
} else {
log.Println("No same node.")
}
}
func alignLists(head1, head2 *Node, m int, n int) (h1, h2 *Node) {
if m > n {
for m > n {
head1 = head1.Next
m--
}
} else if m < n {
for n > m {
head2 = head2.Next
n--
}
}
return head1, head2
}
func findSameNode(head1, head2 *Node) *Node {
if head1 == nil || head2 == nil {
return nil
}
if head1.Value == head2.Value {
return head1
}
head1 = head1.Next
head2 = head2.Next
return findSameNode(head1, head2)
}
func makeList(length int) *Node {
if length == 0 {
return nil
}
head := &Node{
Value: length,
Next: nil,
}
length--
next := head
for length > 0 {
next.Next = &Node{
Value: length,
Next: nil,
}
next = next.Next
length--
}
return head
}
评论