[英]Troubles when trying to “remove by index” on a Purely functional Linked List
As the title states, I have been trying to code singly linked lists and its operations on a purely functional implementation.正如标题所述,我一直在尝试在纯函数实现上编写单链表及其操作。 Things where pretty breezy up until now, lots of recursion, no modification... the works.
直到现在还很轻松的事情,大量的递归,没有修改......作品。
I then tried to implement a function to remove an element from a list, given a certain index.然后我尝试实现一个 function 从列表中删除一个元素,给定一个特定的索引。 I can't for the life of me find a way to implement this without using a counter.
我一辈子都找不到不使用计数器来实现这一点的方法。 It's almost like asking myself, "how to I know how many steps I have walked without myself or an spectator counting them?".
这几乎就像在问自己,“我怎么知道我走了多少步,而没有自己或旁观者数数?”。
Since then I've been on a slump.从那以后,我一直处于低谷。
Here's the code I have so far:这是我到目前为止的代码:
fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>?{
if(list?.data == null){
return list
}
else{
when(index){
0 -> remove(list)
else -> {
when(listSize(list) - index){
0 -> {
return list
}
1 -> {
removeFromTail(list)
}
else -> {
TODO()//HOW?
}
}
}
}
}
}
fun <T> remove(list: ListNode<T>?):ListNode<T>?{
return if(list?.data == null){
list
}
else{
list.next
}
}
fun <T> removeFromTail(list:ListNode<T>?):ListNode<T>?{
return if(list?.data == null){
list
} else{
when(list.next){
null -> null
else -> {
ListNode(list.data, removeFromTail(list.next))
}
}
}
}
Thanks a lot in advance for your help and input.非常感谢您的帮助和意见。
Easy peasy:十分简单:
fun <T> removeFromIndex(list:ListNode<T>?, index: Int):ListNode<T>? = when {
list == null || index < 0 -> list
index == 0 -> list.next
else -> ListNode<T> (
list.data,
removeFromIndex(list.next, index-1)
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.