您的当前位置:首页正文

Golang合并多个有序链表

2024-11-30 来源:个人技术集锦
package main

import (
	"fmt"
)

func main() {
	n1 := &Node{
		val: 1,
		next: &Node{
			val: 4,
			next: &Node{
				val: 5,
			},
		},
	}

	n2 := &Node{
		val: 1,
		next: &Node{
			val: 3,
			next: &Node{
				val: 4,
			},
		},
	}

	n3 := &Node{
		val: 2,
		next: &Node{
			val: 6,
		},
	}
	result := combineNodesBySplit([]*Node{n1, n2, n3})
	result.printNode()
}


func combineNodesBySplit(arr []*Node) *Node {
	if len(arr) < 1 {
		return nil
	}
	if len(arr) == 1 {
		return arr[0]
	}

	mid := len(arr)/2
	left := combineNodesBySplit(arr[:mid])
	right := combineNodesBySplit(arr[mid:])
	return combineSortedLink(left, right)
}


func (n *Node) printNode() {
	for n != nil {
		fmt.Printf("%d \t ", n.val)
		n = n.next
	}
	fmt.Println()
}


type Node struct{
	val int
	next *Node
}

//合并两个有序链表
func combineSortedLink(left, right *Node) *Node {
	if left == nil {
		return right
	}
	if ri
显示全文