首页 > 其他 > 详细

328. Odd Even Linked List

时间:2018-02-27 23:09:55      阅读:254      评论:0      收藏:0      [点我收藏+]

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.

以先奇后偶的序列重排链表。

重新创建一个列表的话,很容易,但题目要求似乎是一次遍历,并且不能创建新的链表,也就是在原链表中调整节点位置。

所以解决思路是,把奇节点插入在奇节点后方,并在原链表中删除对应位置的节点。

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if(!head)
            return head;
        ListNode* p = head;
        ListNode* q = head->next;
        while (q && q->next) {
            ListNode* temp = q->next;   //记录节点
            q->next = q->next->next;    //删除原节点位置
            temp->next = p->next;       //重组链表     
            p->next = temp;             //插入节点
            p = p->next;
            q = q->next;
        }
        return head;
    }
};

 

328. Odd Even Linked List

原文:https://www.cnblogs.com/Zzz-y/p/8481024.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!