• 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;
            }
        }
    };
  • 相关阅读:
    HTML特效代码大全
    PHP网站加网站访问量统计
    定时显示隐藏
    加入收藏 设为首页
    IP和归属地
    手机站的拨打电话和发短信
    Shell运算
    Shell命令替换与变量替换
    $* 和 $@ 的区别
    Shell特殊变量列表
  • 原文地址:https://www.cnblogs.com/ballwql/p/3671416.html
Copyright © 2020-2023  润新知