Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(add_two_linkedlist): 添加两链表相加 #33

Merged
merged 1 commit into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
Loading