Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL
,
return 1->3->5->2->4->NULL
.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
Tips:本题给定一个链表,要求将所有偶数位置的结点聚集在一起,连接在奇数位置的结点之后(调整数组顺序使奇数位于偶数前面)。
我的思路,另外建立一个奇数链表odd,以及一个偶数链表even 遍历原来的链表,奇数位置连接在odd之后,偶数位置连接在even之后。再将even记载odd最后一个节点之后,返回odd的头结点。
package medium; import dataStructure.ListNode; public class L328OddEvenLinkedList { // 空间复杂度为o(n) public ListNode oddEvenList(ListNode head) { // even 偶数 odd奇数 if (head == null) return head; ListNode odd = new ListNode(0); ListNode odd1 =odd; // 先用0占一个头结点,之后直接越过去。 ListNode even = new ListNode(0); ListNode even1 = even; int count = 1; ListNode cur=head; while (cur!= null) { if (count % 2 == 0) { even1.next = cur; System.out.println("even偶数"+even1.val); even1 = even1.next; } else { odd1.next = cur; System.out.println("odd奇数"+odd1.val); odd1 = odd1.next; } count++; cur = cur.next; } even1.next=null; odd1.next = even.next; return odd.next; } public static void main(String[] args) { ListNode head1 = new ListNode(1); ListNode head2 = new ListNode(2); ListNode head3 = new ListNode(3); ListNode head4 = new ListNode(4); ListNode head5 = new ListNode(5); ListNode head6 = new ListNode(6); ListNode head7 = new ListNode(7); ListNode head8 = new ListNode(8); ListNode head9 = new ListNode(9); head1.next = head2; head2.next = head3; head3.next = head4; head4.next = head5; head5.next = head6; head6.next = head7; head7.next = head8; head8.next = head9; head9.next = null; L328OddEvenLinkedList l32 = new L328OddEvenLinkedList(); ListNode head = l32.oddEvenList(head1); while (head != null) { System.out.println(head.val); head = head.next; } } }
原文地址:https://www.cnblogs.com/yumiaomiao/p/8418403.html
时间: 2024-10-08 21:05:22