【发布时间】:2016-10-10 00:26:22
【问题描述】:
我在使用递归概念时遇到了一点困难。
给定一个具有整数值的 LinkedList
L1 = (2->1->4->6->3)
L2= (1->9->6->3)
该函数应该从链表中删除从整数 N 开始的奇数,并返回对新头的引用
即
L1.deleteOdd(2) = > (2->4->6)
L2.deleteOdd(1) = > (6)
我实现了一个正常的迭代函数来完成这项工作,就是这样
public node deleteOdd(int n) {
node head = this.head;
if (head == null)
return head;
while (head != null) {
if (head.data == n) {
node head2 = head;
while (head2.next != null) {
if (head2.next.data % 2 != 0) {
head2.next = head2.next.next;
} else {
head2 = head2.next;
}
}
if (head.data % 2 != 0) {
return head.next;
}
return head;
}
head = head.next;
}
return head;
}
现在我正在尝试做一个递归函数,我尝试做一些事情,但似乎我错过了一些东西。
我的递归函数是
public node DeleteOddR(int n) {
node head = this.head;
if (head == null)
return head;
if (head != null) {
if (head.data == n) {
node head2 = head;
if (head2.next.data % 2 != 0)
{
head2.next = head2.next.next;
} else {
head2 = head2.next;
}
if (head.data % 2 != 0) {
return DeleteOddR(head.next.data);
} else {
head.next = DeleteOddR(head.next.data);
return head;
}
} else {
head = head.next;
}
}
return head;
}
结果是
node f = l1.DeleteOddR(2);
display(f); // Gives- >2->3->4->6
我会很感激帮助..
【问题讨论】:
-
这不是学习递归概念的好例子。为什么要使用带链表的索引?
-
只要知道从哪里开始。它不是真正的“索引”,它是一个数字,我们在链表中搜索它,一旦找到,我们就使用包含该数字的节点作为头部。忘记它之前的所有元素 l=(1,2,3,4,5,6,7,8,9,10,11,12) l.removeOdd(6) -> 6->8->10- >12(我的新名单)
标签: java recursion data-structures linked-list