From 4a9117b416cd1eb665179b2d72d7919d9efba0e8 Mon Sep 17 00:00:00 2001 From: donjuanplatinum Date: Tue, 16 Jul 2024 18:59:05 -0400 Subject: [PATCH] =?UTF-8?q?perf(add=5Ftwo=5Fbinary=5Flinkedlist):=20?= =?UTF-8?q?=E5=AF=B9=E4=BA=8C=E8=BF=9B=E5=88=B6=E9=93=BE=E8=A1=A8=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0=E7=AE=97=E6=B3=95=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/structure/linkedlist.rs | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/src/structure/linkedlist.rs b/src/structure/linkedlist.rs index 80c1482..aa4312d 100644 --- a/src/structure/linkedlist.rs +++ b/src/structure/linkedlist.rs @@ -469,26 +469,23 @@ pub fn add_two_binary_linkedlist(a: LinkedList, b: LinkedList) -> Li let mut result = LinkedList::new(); let (mut p1, mut p2) = (a, b); let mut carry = false; - while p1.front().is_some() || p2.front().is_some() || carry { - let (value1, value2) = match (p1.pop_front(), p2.pop_front()) { - (Some(v1), Some(v2)) => (v1, v2), - (Some(v1), None) => (v1, false), - (None, Some(v2)) => (false, v2), - (None, None) => { - // 当两个链表都为空,只有进位时 - if carry { - carry = false; - (true, false) - } else { - break; - } - } - }; - let xor1 = value1 ^ value2; - // 利用全加器 - let sum = xor1 ^ carry; // 三路异或 判断奇数 - carry = (xor1 & carry) | (value1 & value2); // 三路与 计算偶数进位 - result.push_back(sum); + // sum[0]为第一个链表的值 sum[1]为第二个链表的值 sum[2]为上次进位 + let mut sum = [false; 3]; + while p1.front().is_some() || p2.front().is_some() || sum[2] == true { + if let Some(value) = p1.pop_front() { + sum[0] = value; + } + if let Some(value) = p2.pop_front() { + sum[1] = value; + } + // 第一个链表和第二个链表的奇数判断[异或门] + let xor1 = sum[0] ^ sum[1]; + + // 全加器 + let add_result = xor1 ^ sum[2]; // sum的奇数判断[三路异或门] + sum[2] = (xor1 & sum[2]) | (sum[0] & sum[1]); // 计算偶数进位[两个与门和一个或门] + (sum[0], sum[1]) = (false, false); // 清零 + result.push_back(add_result); } return result;