328-Odd Even Linked List

来源:互联网 发布:js弧线运动 编辑:程序博客网 时间:2024/05/20 09:27

难度:medium
类别:linked list

1.题目描述

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 …

2.算法分析

因为题目对空间有要求,所以不能通过创建新的节点来实现。
通过维护两个链表,一个是奇数链表,一个是偶数链表,最后将这两个链表链到一起即可。代码非常简单,容易理解。

3.代码实现

ListNode* oddEvenList(ListNode* head) {    if (head == NULL || head->next == NULL) return head;    int count = 0;    ListNode* odd = NULL;    ListNode* even = NULL;    ListNode* tempOdd = NULL;    ListNode* tempEven = NULL;    while (head != NULL) {        count++;        if (count % 2 == 1) {            if (odd == NULL) {                tempOdd = head;                odd = tempOdd;            }            else {                tempOdd->next = head;                tempOdd = tempOdd->next;            }        }        else {            if (even == NULL) {                tempEven = head;                even = tempEven;            }            else {                tempEven->next = head;                tempEven = tempEven->next;            }        }        head = head->next;    }    tempEven->next = NULL;    tempOdd->next = even;    return odd;}void printList(ListNode* head) {    while (head != NULL) {        cout << head->val << " ";        head = head->next;    }    cout << endl;}void deleteList(ListNode* head) {    if (head == NULL) return;    if (head->next == NULL) {        delete head;        return;    }    ListNode* temp;    while (head != NULL) {        temp = head;        head = head->next;        delete temp;    }}
原创粉丝点击