【发布时间】:2016-10-16 17:11:26
【问题描述】:
leetcode 上有个问题叫奇偶链表。
上面写着:
给定一个单链表,将所有奇数节点组合在一起,然后是偶数节点。请注意,这里我们讨论的是节点编号,而不是节点中的值。
您应该尝试在适当的位置进行操作。程序应该以 O(1) 的空间复杂度和 O(nodes) 的时间复杂度运行。
示例: 给定 1->2->3->4->5->NULL, 返回 1->3->5->2->4->NULL。
这是我的节点类
public class Node
{
private int value;
private Node next;
public Node(int Value)
{
this.value = Value;
this.next = null;
}
public Node()
{
this.value = -1;
this.next = null;
}
public Node getNext() {
return next;
}public void setNext(Node next) {
this.next = next;
}public int getValue() {
return value;
}public void setValue(int value) {
this.value = value;
}
}
我在列表中有 8 个项目,其值为 1、2、3、4、5、6、7、8。这是我的输出-->1-->3-->5-->7-->2-->4-->6-->8 这是我解决 OddEven 任务的链表方法。
public void oddEven()
{
if(head.getNext() == null)
return;
Node lastOdd = head.getNext(); // gets the value of last odd even in list.
Node current = lastOdd.getNext(); // Puts the reference on the first even index.
Node before = lastOdd; // This node, will always be one index before current Node
int travel = 1, loop;
while(current != null)
{
loop = travel;
// Prvo petlja putuje do sledeceg neparnog elementa
while(loop-- > 0)
{
before = current;
current = current.getNext();
}
if(current == null) // If it is end of the list, exit loop.
break;
before.setNext(current.getNext());
current.setNext(lastOdd.getNext());
lastOdd.setNext(current);
lastOdd = current;
current = before.getNext();
}
}
它在我的电脑上运行良好。但是当我将代码放入 leetcode 时,我得到了它不起作用的错误。但它是相同的代码。这是leetcode的代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head)
{
if(head.next == null)
return head;
ListNode lastOdd = head.next; // gets the value of last odd even in list.
ListNode current = lastOdd.next; // Puts the reference on the first even index
ListNode before = lastOdd;
int travel = 1, loop;
while(current != null)
{
loop = travel;
// Prvo petlja putuje do sledeceg neparnog elementa
while(loop-- > 0)
{
before = current;
current = current.next;
}
if(current == null)
break;
before.next = current.next;
current.next = lastOdd.next;
lastOdd.next = current;
lastOdd = current;
current = before.next;
}
return head;
}
}
这是我得到的错误
对于输入:[1,2,3,4,5,6,7,8]
你的答案:[1,2,4,6,8,3,5,7]
预期答案:[1,3,5,7,2,4,6,8]
但都是同样的方法,我哪里弄错了?
【问题讨论】:
-
if(head.next == null)不检查(head != null)是错误的。
标签: java algorithm linked-list