0
点赞
收藏
分享

微信扫一扫

刷 LeetCode 从零开始学 GoLang(7):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 语法:结构体 struct

  1. 结构体的定义

type struct_variable_type struct {
member definition;
member definition;
...
member definition;
}

  1. 结构体的字面值(Literal)

variable_name := structure_variable_type {value1, value2...valuen}

variable_name := structure_variable_type { key1: value1, key2: value2..., keyn: valuen}

  1. 使用结构体变量,如果要访问结构体成员,需要使用点号 ​​.​​ 操作符
  2. 使用结构体指针访问结构体成员,也是使用 ​​.​​ 操作符

AC 代码

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var head *ListNode = nil
var tail *ListNode = nil

for l1 != nil || l2 != nil {
var cur *ListNode = nil

// 使用结构体指针访问结构体成员,使用 "." 操作符
if l2 == nil || (l1 != nil && l2.Val >= l1.Val) {
cur = l1
l1 = l1.Next
} else {
cur = l2
l2 = l2.Next
}

// 插入 cur 节点到新链表
if head == nil {
head, tail = cur, cur
} else {
tail.Next = cur
tail = tail.Next
}
tail.Next = nil
}

return head
}


举报

相关推荐

0 条评论