Skip to content

Commit 1758552

Browse files
authored
Merge pull request neetcode-gh#2373 from Vishalkulkarni45/main
Update 0021-merge-two-sorted-lists.rs
2 parents fa133f5 + 0e92250 commit 1758552

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
impl Solution {
2+
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32)-> Option<Box<ListNode>> {
3+
let mut list_len=0;
4+
let mut cur=&head;
5+
while let Some(node)=cur{
6+
list_len+=1;
7+
cur=&node.next;
8+
}
9+
let mut ans=Some(Box::new(ListNode{
10+
val:1,
11+
next:head
12+
}));
13+
let mut list=&mut ans;
14+
let mut pos=0;
15+
while let Some(node)=list{
16+
if pos==list_len-n{
17+
node.next=node.next.clone().unwrap().next.take();
18+
break;
19+
}
20+
pos+=1;
21+
list=&mut node.next;
22+
}
23+
ans.unwrap().next.take()
24+
}
25+
}
26+

rust/0021-merge-two-sorted-lists.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,31 @@ impl Solution {
1414
}
1515
}
1616
}
17+
//without recursion
18+
impl Solution {
19+
pub fn merge_two_lists(mut list1: Option<Box<ListNode>>,mut list2: Option<Box<ListNode>>)->Option<Box<ListNode>>{
20+
let mut ans=ListNode::new(1);
21+
let mut cur=&mut ans;
22+
23+
while let (Some(node1),Some(node2))=(list1.as_mut(),list2.as_mut()){
24+
25+
if node1.val<node2.val{
26+
cur.next=list1.take();
27+
list1=cur.next.as_mut().unwrap().next.take();
28+
}
29+
else{
30+
cur.next=list2.take();
31+
list2=cur.next.as_mut().unwrap().next.take();
32+
}
33+
cur=cur.next.as_mut().unwrap();
34+
}
35+
cur.next=if list1.is_some(){
36+
list1
37+
}
38+
else {
39+
list2
40+
};
41+
ans.next
42+
}
43+
}
44+

0 commit comments

Comments
 (0)