gpt4 book ai didi

java - 使用索引递归地从 LinkedList 中删除 Odds

转载 作者:行者123 更新时间:2023-12-01 09:24:25 28 4
gpt4 key购买 nike

我对递归概念有一点困难。

给定一个具有整数值的 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

非常感谢您的帮助..

最佳答案

我写一个可以满足你的要求。
保存前一个节点并使用它进行递归。

public class LinkedList{

public static void main(String[] args) {
LinkedList node0 = new LinkedList(0);
LinkedList node1 = new LinkedList(1);
LinkedList node2 = new LinkedList(2);
LinkedList node3 = new LinkedList(3);
LinkedList node4 = new LinkedList(4);
LinkedList node5 = new LinkedList(5);
LinkedList node6 = new LinkedList(6);
LinkedList node7 = new LinkedList(7);
LinkedList node8 = new LinkedList(8);
node0.setNext(node1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
node6.setNext(node7);
node7.setNext(node8);

node0.removeOddFromVale(3, false);
System.out.println();
}

public void removeOddFromVale(int value,boolean start){
LinkedList head = this;
LinkedList prev = this;

if(!start){
while(head != null){
if(head.value == value){
start = true;
break;
}
prev = head;
head = head.next;
}
}

if(prev != null && head != null){
if(prev == head){
head = head.next;
}

if (head != null) {
if (head.value % 2 == 0) {
prev.next = head.next;
} else {
prev = prev.next;
head = head.next;
}
if (prev != null) {
prev.removeOddFromVale(value, true);
}
}
}

}

private LinkedList next;
private int value;

public LinkedList(int value){
this.value = value;
}

public LinkedList getNext() {
return next;
}
public void setNext(LinkedList next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

关于java - 使用索引递归地从 LinkedList 中删除 Odds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com