题目
奇偶链表
给定一个单链表,把所有的奇数节点和偶数节点分别排在一起
示例:
输入: 2->1->3->5->6->4->7->NULL
输出: 2->3->6->7->1->5->4->NULL
思路
public ListNode oddEvenList1(ListNode head) {if (head == null) return null;ListNode oddList = new ListNode(); //存储奇数节点的结果链表ListNode oddTail = oddList;ListNode evenList = new ListNode(); //存储偶数节点的结果链表ListNode evenTail = evenList;int count = 1; //用来判断奇偶的辅助变量ListNode p = head;while (p != null){ListNode tmp = p.next;if (count % 2 == 1){p.next = null;oddTail.next = p;oddTail = p;} else {p.next = null;evenTail.next = p;evenTail = p;}count++;p = tmp;}//把奇链表的尾指向偶链表的头oddTail.next = evenList.next;return oddList.next;
}