LeetCode Reorder List

Problem Description

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}.

 

Problem Solution

Note: 引入STL list结构来存储链表结点的值,然后通过重排规则改变结点值的顺序并存储在list中,最后再将改变后List中值存储到原linked list中,完成整个操作

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
private:
    list<int> intList;
public:
    
    void reorderList(ListNode *head) {
        if(head==NULL || head->next==NULL)
            return;
        ListNode *p=head;
        int listSize=0;
        while(p)
        {
            intList.push_back(p->val);
            p=p->next;
            listSize++;
        }
        list<int> tmpList; //setup a new list to store the target value
        list<int>::iterator iterBegin=intList.begin();
        for(int i=0;i<listSize/2;++i) //traverse the first half of list
        {
            tmpList.push_back(*iterBegin++); //first push the begin value of list
            tmpList.push_back(intList.back()); //second push the last value of list
            intList.pop_back(); //third, pop the last value of list
        }
        if(listSize%2) //if the list size is odd, last value of list need to be pushed
            tmpList.push_back(intList.back());
        p=head;
        list<int>::iterator tIter=tmpList.begin();
        while(p && tIter != tmpList.end())  //traverse the list and change its value 
        {
            p->val=*tIter++;
            p=p->next;
        }
    }
};

 

 

 

 

 

posted @ 2014-04-17 18:27  ballwql  阅读(192)  评论(0编辑  收藏  举报