返回信息流这是leetcode上的一道题,先按自己的想法写了一下,结果怎么都不对,希望各位大神看看错在哪儿;
输入:1-2-3-4
期望输出:1-3-2-4
实际输出:1-3-2
public class Solution {
public ListNode oddEvenList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode cur=head;
ListNode second=head.next;
ListNode nxt=head.next;
while(cur!=null&&cur.next!=null){
cur.next=cur.next.next;
if(cur.next!=null) cur=cur.next;
}
//这部分有问题,但不知道为什么4出不来;
while(nxt!=null&&nxt.next!=null){
nxt.next=nxt.next.next;
if(nxt.next!=null) nxt=nxt.next;
}
cur.next=second;
return head;
}
public static void main(String[] args){
ListNode node=new ListNode(1);
ListNode h=node;
for(int i=2;i<5;i++){
ListNode p=new ListNode(i);
node.next=p;
node=node.next;
}
Solution s=new Solution();
s.oddEvenList(h);
while(h!=null){
System.out.println(h.val);
h=h.next;
}
}
}
class ListNode{
int val;
ListNode next;
public ListNode(int i) { val=i;}
}
这是一条镜像帖。来源:北邮人论坛 / java / #51510同步于 2016/7/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
Java题目调试求助
vege
2016/7/10镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。