https://leetcode.cn/problems/design-browser-history/
这里我是用双栈实现前进和后退。
#define URL_SIZE 21
#define STACK_SIZE 5000typedef 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) {//跳转至urlchar* 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);
}