**Leetcode_reorder-list

地址:http://oj.leetcode.com/problems/reorder-list/

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

思路:感觉这是一道非常好的题,有比较多基础的知识点。比如两个指针一个步进为一,另一个步进为二来求链表的中间节点,还有就是reverseList是in-place的反转单链表,最后就是把两个长度差小于1的链表锯齿形的merge在一起。

把每个知识点都好好想了一想,这样的题应该多做,打上两颗*.

参考代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head)
    {
        ListNode*pre=NULL, *cur=head, *next=NULL;
        while(cur)
        {
            next=cur->next;
            cur->next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
    void reorderList(ListNode *head) {
        if(head)
        {
            ListNode *p1 = head, *p2 = head, *nxt1 = NULL, *nxt2 = NULL;
            while(p2 && p2->next)
            {
                p1 = p1->next;
                p2 = p2->next;
                if(p2)
                    p2 = p2->next;
            }
            p2 = p1->next;
            p1->next = NULL;
            p1 = head;
            p2 = reverseList(p2);
            //merge
            while(p1 && p2)
            {
                nxt1 = p1->next;
                nxt2 = p2->next;
                p1->next = p2;
                p2->next = nxt1;
                p1 = nxt1;
                p2 = nxt2;
            }
        }
    }
};



 
 
//SECOND TRIAL
class Solution {
private :
     ListNode * reverseList ( ListNode * head )
     {
         if ( ! head || ! head -> next )
             return head ;
         ListNode * p = head , * pre = NULL , * nxt = NULL ;
         while ( p )
         {
             nxt = p -> next ;
             p -> next = pre ;
             pre = p ;
             p = nxt ;
         }
         return pre ;
     }
public :
     void reorderList ( ListNode * head ) {
         if ( ! head || ! head -> next )
             return ;
         ListNode * p1 = head , * p2 = head , * pre = NULL , * nxt1 = NULL , * nxt2 = NULL ;
         while ( p1 )
         {
             p1 = p1 -> next ;
             pre = p2 ;
             if ( p1 )
             {
                 p1 = p1 -> next ;
                 p2 = p2 -> next ;
             }
         }
         p2 = pre -> next ;
         pre -> next = NULL ;
         p2 = reverseList ( p2 );
         p1 = head ;
         while ( p1 && p2 )
         {
             nxt1 = p1 -> next ;
             nxt2 = p2 -> next ;
             p1 -> next = p2 ;
             p1 = p2 -> next = nxt1 ;
             p2 = nxt2 ;
         }
     }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值