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); }
还没有评论,来说两句吧...