赞
踩
public ListNode oddEvenList(ListNode head) { if (head == null) { return null; }else if (head.next == null) { return head; } ListNode odd = new ListNode(0); ListNode oddCur = odd; ListNode even = new ListNode(0); ListNode evenCur = even; while (head != null) { int i = 0; if (i % 2 != 0) { oddCur.next = new ListNode(head.val); oddCur = oddCur.next; }else { evenCur.next = new ListNode(head.val); evenCur = evenCur.next; } head = head.next; } oddCur.next = even.next; return odd.next; }
public class OddEvenList { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ListNode head = null; ListNode node = null; int k = scanner.nextInt(); int i = 7; // while (scanner.hasNextInt()) { while (i-- != 0) { int val = scanner.nextInt(); if (head == null) { node = new ListNode(val); head = node; }else { node.next = new ListNode(val); node = node.next; } }// end while head = partition(head, k); if (head != null) { System.out.print(head.val); head = head.next; while (head != null) { System.out.print(","); System.out.print(head.val); head = head.next; } } System.out.println(); } public ListNode oddEvenList(ListNode head) { if (head == null) { return null; }else if (head.next == null) { return head; } ListNode odd = new ListNode(0); ListNode oddCur = odd; ListNode even = new ListNode(0); ListNode evenCur = even; while (head != null) { int i = 0; if (i % 2 != 0) { oddCur.next = new ListNode(head.val); oddCur = oddCur.next; }else { evenCur.next = new ListNode(head.val); evenCur = evenCur.next; } head = head.next; } oddCur.next = even.next; return odd.next; } /** * 给定一个链表和一个整数k,将链表分成两部分,比k小的放在左边,比k大的放在右边;并且左右两部分各自的相对顺序不变。 * @param head * @param k * @return */ /** * 输入:k=5, head:1->9->7->3->6->5->2 * 输出:1->3->5->2->9->7->6 */ public static ListNode partition(ListNode head, int k) { if (head == null || head.next == null) { return head; } ListNode small = new ListNode(0); ListNode smallCur = small; ListNode large = new ListNode(0); ListNode largeCur = large; while (head != null) { if (head.val <= k) { smallCur.next = new ListNode(head.val); smallCur = smallCur.next; }else { largeCur.next = new ListNode(head.val); largeCur = largeCur.next; } head = head.next; } smallCur.next = large.next; return small.next; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。