每日一题《leetcode--1472.设计浏览器历史记录》

每日一题《leetcode--1472.设计浏览器历史记录》

码农世界 2024-05-24 前端 66 次浏览 0个评论

https://leetcode.cn/problems/design-browser-history/


 这里我是用双栈实现前进和后退。

#define URL_SIZE 21
#define STACK_SIZE 5000
typedef struct {
    char *BackStack[STACK_SIZE];    //回退栈
    char *ForwardStack[STACK_SIZE]; //前进栈
    int BackTop;    //回退栈的栈顶下标
    int ForwardTop;  //前进栈的栈顶下标
} BrowserHistory;
char *CreatUrl(char* url)
{
    char *ChUrl = (char*)malloc(sizeof(char) * URL_SIZE);
    strcpy(ChUrl,url);
    return ChUrl;
}
BrowserHistory* browserHistoryCreate(char* homepage) {
    BrowserHistory* obj = (BrowserHistory*)malloc(sizeof(BrowserHistory));
    memset(obj, 0, sizeof(BrowserHistory));
    obj -> BackTop = -1;
    obj -> ForwardTop = -1;
    char *ChUrl = CreatUrl(homepage);
    obj->BackStack[++(obj->BackTop)] = ChUrl;
    return obj;
}
void browserHistoryVisit(BrowserHistory* obj, char* url) {
    //跳转至url
    char* ChUrl = CreatUrl(url);
    obj->BackStack[++(obj->BackTop)] = ChUrl;
    //跳转完成后需要把前进栈中的数据给清空,里面的url不能被访问
    while(obj->ForwardTop >= 0)
    {
        free(obj->ForwardStack[obj->ForwardTop]);
        obj->ForwardStack[obj->ForwardTop] = NULL;
        obj->ForwardTop--;
    }
}
char* browserHistoryBack(BrowserHistory* obj, int steps) {
    int count = 0;  //记录回退的步数
    while(count < steps && obj->BackTop > 0)
    {
        //把回退栈中栈顶的数据放入前进栈中
        obj->ForwardStack[++(obj->ForwardTop)] = obj->BackStack[obj->BackTop];
        obj->BackStack[obj->BackTop] = NULL;
        obj->BackTop--;
        count++;
    }
    return obj->BackStack[obj->BackTop];
}
char* browserHistoryForward(BrowserHistory* obj, int steps) {
    int count = 0;  //记录前进的步数
    while(count < steps && obj->ForwardTop >= 0)
    {
        obj->BackStack[++(obj->BackTop)] = obj->ForwardStack[obj->ForwardTop];
        obj->ForwardStack[obj->ForwardTop] = NULL;
        obj->ForwardTop--;
        count++;
    }
    return obj->BackStack[obj->BackTop];
}
void browserHistoryFree(BrowserHistory* obj) {
    while(obj->BackTop >= 0)
    {
        free(obj->BackStack[obj->BackTop]);
        obj->BackTop--;
    }
    while(obj->ForwardTop >= 0)
    {
        free(obj->ForwardStack[obj->ForwardTop]);
        obj->ForwardTop--;
    }
    free(obj);
}

转载请注明来自码农世界,本文标题:《每日一题《leetcode--1472.设计浏览器历史记录》》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,66人围观)参与讨论

还没有评论,来说两句吧...

Top