• [Leetcode] Peeking Iterator, Solution


    Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().

    Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].
    Call next() gets you 1, the first element in the list.
    Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.
    You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

    [Thoughts]
    链表的一道设计题。next其实在这里就是获取头元素的值,并移动到下一个元素。peek在这里就是返回当前元素的值。

    [Code]
    1:  // Below is the interface for Iterator, which is already defined for you.  
    2: // **DO NOT** modify the interface for Iterator.
    3: class Iterator {
    4: struct Data;
    5: Data* data;
    6: public:
    7: Iterator(const vector<int>& nums);
    8: Iterator(const Iterator& iter);
    9: virtual ~Iterator();
    10: // Returns the next element in the iteration.
    11: int next();
    12: // Returns true if the iteration has more elements.
    13: bool hasNext() const;
    14: };
    15: class PeekingIterator : public Iterator {
    16: public:
    17: PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    18: // Initialize any member here.
    19: // **DO NOT** save a copy of nums and manipulate it directly.
    20: // You should only use the Iterator interface methods.
    21: this->length = nums.size();
    22: this->nums = &nums;
    23: }
    24: // Returns the next element in the iteration without advancing the iterator.
    25: int peek() {
    26: if(currentIndex < length) {
    27: return (*this->nums)[currentIndex];
    28: }
    29: return -1;
    30: }
    31: // hasNext() and next() should behave the same as in the Iterator interface.
    32: // Override them if needed.
    33: int next() {
    34: if(currentIndex < length) {
    35: currentIndex ++;
    36: return (*this->nums)[currentIndex-1];
    37: }
    38: return -1;
    39: }
    40: bool hasNext() const {
    41: return currentIndex < length;
    42: }
    43: private:
    44: int currentIndex = 0;
    45: int length = 0;
    46: const vector<int>* nums = NULL;
    47: };

    github:https://github.com/codingtmd/leetcode/blob/master/src/Peeking_Iterator.cpp


  • 相关阅读:
    Ubuntu开源推进全面展开抢占微软市场
    sb600芯片下,操持ubuntu没有声响的要领(ubuntu8.04上乐成)
    centos下设置ssh衔接工夫
    入门linux
    centos下进入单用户情势
    ubuntu hardy下的smtp管事
    MySQL数据库中查找执行从命慢的SQL语句
    mac、xp、linux共存
    Linux和Windows终究哪个更适用
    Debian下的mozilla眷属
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078840.html
Copyright © 2020-2023  润新知