前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 284. Peeking Iterator

LeetCode 284. Peeking Iterator

作者头像
ShenduCC
发布2020-05-22 16:06:19
3410
发布2020-05-22 16:06:19
举报
文章被收录于专栏:算法修养

题目

再维护一个iterator ,用来实现peek

代码语言:javascript
复制
/*
 * Below is the interface for Iterator, which is already defined for you.
 * **DO NOT** modify the interface for Iterator.
 *
 *  class Iterator {
 *		struct Data;
 * 		Data* data;
 *		Iterator(const vector<int>& nums);
 * 		Iterator(const Iterator& iter);
 *
 * 		// Returns the next element in the iteration.
 *		int next();
 *
 *		// Returns true if the iteration has more elements.
 *		bool hasNext() const;
 *	};
 */

class PeekingIterator : public Iterator {
public:
    Iterator* iter;
    int _next;
	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
	    // Initialize any member here.
	    // **DO NOT** save a copy of nums and manipulate it directly.
	    // You should only use the Iterator interface methods.
        iter = new Iterator(nums);
        if(nums.size()!=0)
            _next = nums[0];
        if(iter->hasNext())
            iter->next();
	    
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	int peek() {
        
        return _next;
        
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	int next() {
        
        if(iter->hasNext())
             _next = iter->next();
	    return 	Iterator::next();
	}
	
	bool hasNext() const {
	    
        return Iterator::hasNext();
	}
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-05-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档