【发布时间】:2021-03-11 18:20:23
【问题描述】:
我正在尝试解决一个问题,其中给我一个带有数据整数的 LinkedList,我的任务是将列表拆分为两个单独的列表,一个具有所有偶数位置,一个具有所有奇数位置。
输入:0 1 2 3 0 -4 -5
ListNode 类:
public class ListNode
{
public int data;
public ListNode next;
public ListNode(int _data)
{
data = _data;
next = null;
}
}
驱动方法:
public static void main(String [] args) {
MyList L = new MyList();
ListNode head = L.getHead(); // Get the head node of the linked list.
System.out.print("INPUT: ");
print(head);
ListNode [] R = split(head); // Split into two list. The first list contains all elements in odd positions, the second contains all elements at even positions.
System.out.println("Printing the list with odd positions");
print(R[0]);
System.out.println("Printing the list with even positions");
print(R[1]);
}
我正在努力想办法做到这一点,我没有得到任何帮助方法来添加节点,这是我尝试过但无法正常工作的方法。
private static ListNode[] split(ListNode L)
{
ListNode[] ret = new ListNode[2];
for (ListNode cur = L; cur != null; cur = cur.next)
{
if ((cur.data % 2) == 0)
{
ret[1] = cur;
ret[1].data = cur.data;
System.out.print("CURRENT EVEN LIST IS ");
print(ret[1]);
}
else
{
ret[0] = cur;
ret[0].data = cur.data;
System.out.print("CURRENT ODD LIST IS ");
print(ret[0]);
}
}
return ret;
}
这是我得到的输出:
INPUT: 0 1 2 3 0 -4 -5
CURRENT EVEN LIST IS 0 1 2 3 0 -4 -5
CURRENT ODD LIST IS 1 2 3 0 -4 -5
CURRENT EVEN LIST IS 2 3 0 -4 -5
CURRENT ODD LIST IS 3 0 -4 -5
CURRENT EVEN LIST IS 0 -4 -5
CURRENT EVEN LIST IS -4 -5
CURRENT ODD LIST IS -5
Printing the list with odd positions
-5
Printing the list with even positions
-4 -5
我希望有人能带领我走上正确的道路,我知道我的尝试是错误的,因为它总是复制整个列表,但我知道我错过了一些东西。有递归方法吗?
谢谢
【问题讨论】:
-
你想要递归,但你展示的方法是迭代的
-
是的,我正在寻找一个正确方向的观点,说明如何递归地处理这个问题,或者如果可能的话,帮助纠正我的迭代方法。
标签: java data-structures linked-list nodes