Skip to content

Commit

Permalink
feat(add_two_linkedlist): 添加两链表相加
Browse files Browse the repository at this point in the history
  • Loading branch information
donjuanplatinum committed Jul 7, 2024
1 parent 44e1a29 commit e85bc52
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/structure/linkedlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ impl<T> LinkedList<T> {
}
None
}
/// 消耗linkedlist变成vec
pub fn to_vec(mut self) -> Vec<T> {
let mut vec = vec![];
while self.head.is_some() {
Expand Down Expand Up @@ -429,3 +430,29 @@ impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
return new_linkedlist;
}
}

/// 将两个链表相加 每个节点为0-9
/// ```
/// use algori::structure::LinkedList;
/// use algori::structure::linkedlist::add_two_linkedlist;
/// let a: LinkedList<i32> = [1,3,2,5,5,2].into();
/// let b: LinkedList<i32> = [2,3,1,9,1,4,6,8].into();
/// assert_eq!(&add_two_linkedlist(a,b).to_vec(),&[3,6,3,4,7,6,6,8]);
/// ```
pub fn add_two_linkedlist(a: LinkedList<i32>, b: LinkedList<i32>) -> LinkedList<i32> {
let mut result = LinkedList::new();
let mut current = &mut result;
let (mut p1, mut p2) = (a, b);
let mut sum = 0i32;
while p1.front().is_some() || p2.front().is_some() || sum != 0 {
if let Some(value) = p1.pop_front() {
sum += value;
}
if let Some(value) = p2.pop_front() {
sum += value;
}
current.push_back(sum % 10);
sum = sum / 10;
}
return result;
}
2 changes: 1 addition & 1 deletion src/structure/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
mod heap;
mod linkedlist;
pub mod linkedlist;
pub use self::heap::*;
pub use self::linkedlist::LinkedList;

0 comments on commit e85bc52

Please sign in to comment.