leetcode reorder-list

链表的重排序

问题描述:

Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

https://oj.leetcode.com/problems/reorder-list/点击打开链接

问题分析:

问题求解方法很简单,不做进一步分析。

定义: 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
LisNode *head  为待处理的链表。

1. 将链表head分为两份,前半部分链表list1, 后半部分链表list2

2. list2逆序

3. list1, list2合并

void divideList(ListNode *head, ListNode* &list1, ListNode* &list2);
ListNode* reverse(ListNode *head);
ListNode* merge(ListNode *a, ListNode *b);

C语言代码:

void reorderList(ListNode *head) 
    {
        /* 空表或者只有一个元素不需要reorder */
        if (!head || !head->next)
        {
            return;
        }
        
        /* 
         * p1 前半部分头指针
         * p2 后半部分头指针
         * 前半部分可能比后半部分多一个元素 
         *
         */
        ListNode *p1, *p2;
        p1 = head; 
        
        ListNode *slow, *fast, *tail, *p;
        slow = head;
        fast = head;
        while (fast)
        {
            tail = slow;
            slow = slow->next;
            fast = fast->next ? fast->next->next : NULL;
        }
        tail->next = NULL;
        p2 = slow;
        
        p = p2->next;
        p2->next = NULL;
        tail = p2;
        while (p)
        {
            p2 = p;
            p = p->next;
            p2->next = tail;
            tail = p2;
        }
        
        while (p1 && p2)
        {
            ListNode *prv = p1;
            p1 = p1->next;
            prv->next = p2;
            p2 = p2->next;
            prv->next->next = p1;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值