Leetcode 21:Merge Two Sorted Lists(golang实现合并两条已经排序的链表)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 21:Merge Two Sorted Lists(golang实现合并两条已经排序的链表)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
21.Merge Two Sorted Lists
題目鏈接:題目鏈接
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4解題代碼:
golang語言
/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {var head *ListNodeif l1==nil && l2==nil{return l1}if l1!=nil && l2==nil{ head=l1l1=l1.Next}if l2!=nil && l1==nil{ head=l2l2=l2.Next}if l2!=nil && l1!=nil{ if l1.Val<l2.Val{head=l1l1=l1.Next}else {head=l2l2=l2.Next}}var pre *ListNode=headvar node *ListNodefor l1!=nil &&l2!=nil {if l1.Val<l2.Val{node=l1l1=l1.Next}else {node=l2l2=l2.Next}pre.Next=nodepre=node}if l1!=nil {node=l1pre.Next=nodepre=nodel1=l1.Next}if l2!=nil {node=l2pre.Next=nodepre=nodel2=l2.Next}return head}總結(jié)
以上是生活随笔為你收集整理的Leetcode 21:Merge Two Sorted Lists(golang实现合并两条已经排序的链表)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NUTCH的安装与测试
- 下一篇: mac搭建mongodb