奇偶链表~字节题库

740 阅读2分钟

328. 奇偶链表

Difficulty: 中等

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。

示例 1:

输入: 1->2->3->4->5->NULL
输出: 1->3->5->2->4->NULL

示例 2:

输入: 2->1->3->5->6->4->7->NULL 
输出: 2->3->6->7->1->5->4->NULL

说明:

  • 应当保持奇数节点和偶数节点的相对顺序。
  • 链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。

Solution

Language: java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
              // write code here
        //首先想到是先用List来存储所有节点,奇数放前面,偶数放后面
         List<Integer> list = new ArrayList();
         ListNode current =  head;
        while(current != null)
        {
            list.add(current.val);
            current = current.next;
        }

        //将奇数放前面,偶数放后面
        List<Integer> oddList = new ArrayList();
        for(int i = 0; i < list.size(); )
        {
            oddList.add(list.get(i));
            i = i + 2;
        }
        for(int i = 1; i < list.size(); )
        {
             oddList.add(list.get(i));
             i = i + 2;
        }
      
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        //List值重新生产链表
        for(int k = 0; k < oddList.size(); k++)
        {
            cur.next = new ListNode(oddList.get(k));
            cur = cur.next;
        }
        cur.next = null;
        return dummy.next;
    }
}

  • 打败的人不是很多,而且题目要用空间复杂度是O(1),我们这里借助了两个List来存放链表的值,显示这种在面试中是不能得分的,所以我们要继续优化
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
              // write code here
        ListNode oddDummy = new ListNode();
        ListNode oddHead = oddDummy;
        ListNode evenDummy = new ListNode();
        ListNode evenHead = evenDummy;
        boolean isOdd = true;
        while(head != null)
        {
            if(isOdd)
            {
                oddHead.next = head;
                oddHead = oddHead.next;
            }
            else
            {
                evenHead.next = head;
                evenHead = evenHead.next;
            }
            isOdd = !isOdd;
            head = head.next;
        }
        //偶数链表接到奇数链表的后面
        oddHead.next = evenDummy.next;
        evenHead.next = null;
        return oddDummy.next;
    }
}