LeetCode第2题:两数相加(AHK v2)
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their
nodes contain a single digit. Add the two numbers and return it as a
linked list. You may assume the two numbers do not contain any leading
zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5
-> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
————————————————
; AutoHotkey v2 是一个功能强大的脚本语言,它支持面向对象的编程范式。下面是一个简单的面向对象的链表(LinkedList)实现示例,使用AutoHotkey v2编写:
; ```autohotkey
#Requires AutoHotkey v2.0
; 定义节点类
class Node {__New(value) { this.value := valuethis.next := ""}
}; 定义链表类
class LinkedList {; 初始化链表__New() {this.head := ""}; 向链表尾部添加元素Add(value) {; node := Node(value)_node := Node(value)if (!this.head) {; this.head := nodethis.head := _node} else {current := this.headLoop {if (!current.next) {break}current := current.next}; current.next := nodecurrent.next := _node}}; 根据索引获取元素Get(index) {current := this.head; idx := 0idx := 1while (current) {if (idx == index) {return current.value}idx++current := current.next}return -1 ; 索引无效}; 移除元素(按值)Remove(value) {prev := ""current := this.headwhile (current) {if (current.value == value) {if (!prev) {this.head := current.next} else {prev.next := current.next}break}prev := currentcurrent := current.next}}; 获取链表长度Length() {count := 0current := this.headwhile (current) {count++current := current.next}return count}; 打印链表Print() {current := this.headwhile (current) {; MsgBox, % "Value: " current.valueMsgBox "Value: " current.valuecurrent := current.next}}
}; 使用示例class Solution {static addTwoNumbers( l1, l2) {; head := ListNode(0)head := LinkedList()head.Add(0)temp := headsum := 0while(l1!="" || l2!="" || sum!=0){if(l1!=""){sum+=l1.vall1 :=l1.next}if(l2!=""){sum+=l2.vall2:=l2.next}; a := sum %10a := Mod(sum ,10); next_ := ListNode(a)next_ := LinkedList.add(a)temp.next := next_temp := temp.nextsum := sum/10}return head.next}
}
l1:= LinkedList()
l1.Add(2)
l1.Add(4)
l1.Add(3)
l2:= LinkedList()
l2.Add(7)
l2.Add(0)
l2.Add(8)
Solution.addTwoNumbers(l1,l2).Print()