【leetcode】Odd Even Linked list


题目看错了,我把所有的奇数放到了所有偶数的前面。

下面是代码对应的不是这个题目。

package myTest;
import java.util.Random;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
import myTest.ListNode;

public class Solution {

    public static ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null)
        	return head;
        ListNode t =  head;
        ListNode flag = null; // flag 指向最后一个奇数
        if(t.val%2 == 1 || t.val%2 == -1)
        {
        	flag = t;
        }
        while( t.next != null ){
        	if ( t.next.val%2 == 1 ||  t.next.val%2 == -1)
        	{
        		if (flag == null)
        		{
        			flag = t.next;
        			t.next = flag.next;
        			flag.next = head;
        			head = flag;
        		}
        		else
        		{	
        			if (flag.next == t.next) // 相邻奇数
        				break;
        			ListNode temp = flag;
        			ListNode temp2 = flag.next;
        			flag = t.next;
        			t.next = flag.next;
        			temp.next = flag;
        			flag.next = temp2;
        		}
        	}
        	else
        		t = t.next;
        }
    	return head;
    }
    
    private static void outPut(ListNode head){
    	while( head != null )
    	{
    		System.out.print(head.val+", ");
    		head = head.next;
    	}
    	System.out.println();
    }

    public static void main(String args[])
    {	
    	ListNode head = null;
    	for(int i = 0;i < 10;i++){
    		Random random = new Random();
    		int pos = random.nextInt() % 100 > 0 ? random.nextInt() % 100 : -(random.nextInt() % 100);
    		ListNode t = new ListNode(pos);
    		t.next = null;
    		if( head != null){
    			t.next = head;
    		}
    		head = t;
    	}
    	
    	outPut(head);
    	outPut(oddEvenList(head));
    }
}


下面是代码


public static ListNode oddEvenList(ListNode head) {
    	if(head == null)  
            return head;  
	    ListNode first = head;  
	    ListNode second = head.next;  
	    ListNode temp = second;  
	    while(second != null && second.next != null)  
	    {  
	        first.next = second.next;  
	        first = first.next;  
	        second.next = first.next;  
	        second = second.next;  
	    }  
	    first.next = temp;  
	    return head;  
    }

写个链表都写的这么费劲呢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值