数据结构定义
pub struct ListNode {
data: u32,
next: Option<Box<ListNode>>
}
pub struct List {
head: Option<Box<ListNode>>,
}
}
基本操作实现
impl ListNode {
fn new(val: u32) -> ListNode {
ListNode {
data: val,
next: None,
}
}
}
impl List {
pub fn new() -> List {
List {
head: None,
}
}
pub fn push(&mut self, val: u32) {
let mut new = Box::new(ListNode::new(val));
new.next = self.head.take();
self.head = Some(new)
}
pub fn pop(&mut self) -> Option<u32> {
match self.head.take() {
Some(mut node) => {
self.head = node.next.take();
Some(node.data)
},
None => {
None
}
}
}
// 顺序插入
pub fn insert_sort(&mut self, val: u32) {
let mut new = Box::new(ListNode::new(val));
if let Some(mut cur) = self.head.as_mut() {
if cur.data >= val {
new.next = self.head.take();
self.head = Some(new);
} else {
while cur.next.is_some() && cur.next.as_ref().unwrap().data < val {
cur = cur.next.as_mut().unwrap();
}
new.next = cur.next.take();
cur.next = Some(new);
}
} else {
self.head = Some(new);
}
}
// 移除值为val的节点
pub fn remove(&mut self, val: u32) {
if let Some(mut cur) = self.head.as_mut() {
if cur.data == val {
let next = cur.next.take();
self.head = next;
} else {
while cur.next.is_some() {
if cur.next.as_ref().unwrap().data == val {
let next = cur.next.as_mut().unwrap();
cur.next = next.next.take();
} else {
cur = cur.next.as_mut().unwrap();
}
}
}
}
}
}
链表迭代器实现
pub struct IntoIter(List);
impl Iterator for IntoIter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
self.0.pop()
}
}
impl IntoIterator for List {
type Item = u32;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
IntoIter(self)
}
}
pub struct Iter<'a> {
next: Option<&'a ListNode>,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a u32;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|node| {
self.next = node.next.as_deref();
&node.data
})
}
}
impl<'a> IntoIterator for &'a List {
type Item = &'a u32;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
Iter {
next: self.head.as_deref(),
}
}
}
pub struct IterMut<'a> {
next: Option<&'a mut ListNode>,
}
impl<'a> Iterator for IterMut<'a> {
type Item = &'a mut u32;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|node| {
self.next = node.next.as_deref_mut();
&mut node.data
})
}
}
impl<'a> IntoIterator for &'a mut List {
type Item = &'a mut u32;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> Self::IntoIter {
IterMut {
next: self.head.as_deref_mut(),
}
}
}
相关参考