zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    };
  • 相关阅读:
    ICS SIP Call移植
    ubuntu常用软件安装
    ubuntu开机自动设置屏幕亮度
    书摘《苹果是方的》
    dbml 添加时自动生成 Guid & DataTime
    English 中有趣的a和d
    asp.net 生成ul控件
    lambda c# 3.0
    0809 END Lakers
    linq c# 3.0
  • 原文地址:https://www.cnblogs.com/ballwql/p/3671416.html
Copyright © 2011-2022 走看看