合并两个有序的链表Python和Go代码

Python Version

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None

class Solution:
    def merge_two_list(self,l1:ListNode,l2:ListNode)->ListNode:
        #pre是哨兵节点,head是每次要移动的
        pre=head = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                #head的next指向l1
                head.next = l1
                #l1前移
                l1 = l1.next
            else:
                head.next = l2
                l2 = l2.next  
            #指向比较完之后数据,进行下一轮比较    
            head = head.next
        #剩下的部分是没有比较的             
        head.next = l1 if l1 is not None else l2
       
        return pre.next

def traverse_list(l):
    cursor = l
    while cursor is not None:
        print(cursor.val)
        cursor = cursor.next
            

if __name__ == "__main__":
    l = ListNode(1)
    l.next = ListNode(20)    
    l.next.next = ListNode(200) 
    l.next.next.next = ListNode(2001)

    l2 = ListNode(2)
    l2.next = ListNode(21)
    s = Solution() 
    new_l=s.merge_two_list(l,l2)    
    traverse_list(new_l)              

Go Version

package main
import "fmt"
type ListNode struct {
      Val int
      Next *ListNode
} 
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    var head *ListNode
    var pre *ListNode
    head = &ListNode{Val:-1}
    pre = head
    for l1!=nil && l2!=nil {
        if l1.Val <= l2.Val{
            head.Next = l1
            l1 = l1.Next
        }else{
            head.Next = l2
            l2 = l2.Next
        }
        head = head.Next
    }
    if l1!=nil{
        head.Next = l1

    }
    if l2!=nil{
        head.Next = l2
    }
    return pre.Next
}

func reverse(l *ListNode){
    cursor:=l
    for cursor!=nil {
        fmt.Println(cursor.Val)
        cursor= cursor.Next
    }
}
func main(){
    l1:=&ListNode{Val:1}
    l1.Next = &ListNode{Val:2}
    l1.Next.Next = &ListNode{Val:9}

    l2:=&ListNode{Val:3}
    l2.Next = &ListNode{Val:4}
    l2.Next.Next = &ListNode{Val:8}
    l2.Next.Next.Next = &ListNode{Val:10}
    new_l:=mergeTwoLists(l1,l2)
    reverse(new_l)
}

猜你喜欢

转载自www.cnblogs.com/c-x-a/p/12289413.html
今日推荐