0
点赞
收藏
分享

微信扫一扫

Golang合并多个有序链表

624c95384278 2022-01-25 阅读 42
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 right == nil {
		return left
	}

	if left.val < right.val {
		left.next = combineSortedLink(left.next, right)
		return left
	} else {
		right.next = combineSortedLink(left, right.next)
		return right
	}
}

通过分治法+递归将多个有序链表合并成一个有序链表

结果:1      1      2      3      4      4      5      6     

举报

相关推荐

0 条评论