[LeetCode] Odd Even Linked List

简介: 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

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…

解题思路

分别将奇数和偶数位置的结点连接起来,最后再把奇数和偶数链表连接起来。

实现代码

//Runtime: 1 ms
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode oddTail = head;
        ListNode even = head.next;
        ListNode evenTail = even;
        int i = 1;
        ListNode cur = head.next.next;
        while (cur != null) {
            if (i++ % 2 == 1) {
                oddTail.next = cur;
                oddTail = oddTail.next;
            } else {
                evenTail.next = cur;
                evenTail = evenTail.next;
            }
            cur = cur.next;
        }
        evenTail.next = null;
        oddTail.next = even;

        return head;
    }
}
目录
相关文章
|
5月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
20 1
|
5月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
26 0
|
5月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
19 0
|
4月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
27 0
|
10月前
|
C++
【PAT甲级 - C++题解】1133 Splitting A Linked List
【PAT甲级 - C++题解】1133 Splitting A Linked List
53 0
|
10月前
|
C++
【PAT甲级 - C++题解】1074 Reversing Linked List
【PAT甲级 - C++题解】1074 Reversing Linked List
43 0
|
10月前
|
机器学习/深度学习 存储 C++
【PAT甲级 - C++题解】1052 Linked List Sorting
【PAT甲级 - C++题解】1052 Linked List Sorting
60 0
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
|
存储 C++
线性表的链式存储结构 单链表(Singly Linked List) C++
线性表的链式存储结构 单链表(Singly Linked List) C++
|
1月前
|
存储 安全 Java
java集合框架及其特点(List、Set、Queue、Map)
java集合框架及其特点(List、Set、Queue、Map)

热门文章

最新文章