leetcode:Odd Even Linked List

来源:互联网 发布:中医 数据库 编辑:程序博客网 时间:2024/06/05 20:20

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.


题目分析:


给定一个单向链表,要求将所有的奇数位置的节点放到前面,如1->2->3->4->5->NULL,则进行变换后,得到的链表为1->3->5->2->4->NULL。


解题思路:

1)一遍遍历链表,将链表分为奇数链表和偶数链表

2)将1)中得到的奇数链表与偶数链表进行挂接,从而得到最终的奇偶链表。


代码:

// 奇偶链表操作
struct ListNode *oddEvenList(struct ListNode *head)
{
    // 奇数链表 
    struct ListNode *odd = (struct ListNode *) malloc (sizeof(struct ListNode));
    // 偶数链表
    struct ListNode *even = (struct ListNode *) malloc (sizeof(struct ListNode));
    struct ListNode *odd1 = odd;
    struct ListNode *even1 = even;
    if (head == NULL || head->next == NULL || head->next->next == NULL)
        return head;
    struct ListNode *o = head;
    struct ListNode *e = head->next;
    // 循环分割出奇数链表和偶数链表 
    while (true)
    {
        odd1->next = o;
        odd1 = odd1->next;
        even1->next = e;
        even1 = even1->next;
        if (e != NULL)
            o = o->next->next;
        else 
            break;
        if (o != NULL)
            e = e->next->next;
        else
            break;
    }
    // 处理奇数链表的尾部 
    if (o != NULL)
    {
        odd1->next = o;
        odd1 = odd1->next;
    } 
    // 处理偶数链表的尾部 
    if (e != NULL)
    {
        even1->next = e;
        even1 = even1->next;
    }
    // 处理链表尾部,并将两个链表进行挂接
    if (even1 != NULL)
        even1->next = NULL;
    odd1->next = even->next;
    return odd->next; 


原创粉丝点击