Golangbyte
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list by splicing together the nodes of the first two lists. Return the head of the merged linked list.

LeetCode Problem

Solution in Go

package main

import (
	"fmt"
)

type ListNode struct {
	Value int
	Next  *ListNode
}

func Traverse(head *ListNode) {
	if head == nil {
		fmt.Println("no ll")
	} else {
		current := head
		for current != nil {
			fmt.Println(current.Value)
			current = current.Next
		}
	}
}

func (l *ListNode) Insert(val int) *ListNode {
	NewNode := &ListNode{Value: val, Next: nil}
	if l == nil {
		l = NewNode
	} else {
		current := l
		for current.Next != nil {
			current = current.Next
		}
		current.Next = NewNode
	}
	return l
}

func linkedListMerger(l1, l2 *ListNode) *ListNode {
	result := &ListNode{}
	current := result

	for l1 != nil && l2 != nil {
		if l1.Value < l2.Value {
			current.Next = l1
			l1 = l1.Next
		} else {
			current.Next = l2
			l2 = l2.Next
		}
		current = current.Next
	}

	if l1 == nil {
		current = l2
	} else {
		current = l1
	}
	return result.Next
}

func main() {
	ll1 := &ListNode{Value: 1}
	ll2 := &ListNode{Value: 2}

	ll1.Insert(5)
	ll1.Insert(7)
	ll1.Insert(9)
	ll1.Insert(11)

	ll2.Insert(4)
	ll2.Insert(6)
	ll2.Insert(8)
	ll2.Insert(10)

	for ll1.Next != nil {
		fmt.Println(ll1.Value)
		ll1 = ll1.Next
	}
	fmt.Println("----------")
	Traverse(ll2)
	fmt.Println("----------")
	mergedLinkedList := linkedListMerger(ll1, ll2)
	fmt.Println("----------merged linked list-----------")

	Traverse(mergedLinkedList)
}