328. Odd Even Linked List

来源:互联网 发布:mina 接收不到数据 编辑:程序博客网 时间:2024/06/08 00:35

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.

大概意思是:将奇数序号的节点放在一起,偶数序号节点放在一起。

分析如下:
比如一个链表是1->2->4->3->5(这里故意序号打乱)
使用3个指针,一个指针指向奇数序号的头结点,一个指向偶数序号的头结点,最后一个是偶数的变换节点,因为最后需要将两段链表连接,所以需要一个偶数序号头结点。

oddhead指向第一个节点1
evenhead指向第二个节点2(不动)
suc是偶数节点的移动节点指向第二个节点2

一下是算法运行的手画图:
oh是oddhead,eh是evenhead

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* oddEvenList(ListNode* head) {        if(!head) return head;        ListNode *oddhead=head,*evenhead=head->next,*suc=evenhead;        while(suc!=NULL&&suc->next!=NULL)        {            oddhead->next=oddhead->next->next;            suc->next=suc->next->next;            oddhead=oddhead->next;            suc=suc->next;        }        oddhead->next=evenhead;        return head;    }};
原创粉丝点击