1472. Design Browser History - Medium

前往題目

想法

  • Double linkedlist

思路

簡單的一道題,但要細心

  1. 自己寫一個class,可以儲存上一個和下一個node藉此組成有雙向連接的list
    • visit: 在尾巴加一個新的node
    • back: 往後直到步數為零或是到頭了
    • forward: 往前直到步數為零或是到底了

Code

class BrowserHistory {
    private class Node {
        Node prev;
        Node next;
        String url;

        public Node(String url) {
            this.url = url;
            prev = null;
            next = null;
        }
    }

    Node cur;

    public BrowserHistory(String homepage) {
        cur = new Node(homepage);
    }
    
    public void visit(String url) {
        // add the new url
        cur.next = new Node(url);
        
        // Assign the new node's prev node to the current one
        cur.next.prev = cur;

        // Move the pointer to the latest node
        cur = cur.next; 
    }
    
    public String back(int steps) {
        // Until the first element or the steps have exhuasted
        while (cur.prev != null && steps > 0) {
            cur = cur.prev;
            --steps;
        }
        return cur.url;
    }
    
    public String forward(int steps) {
        // Until the end or the steps have exhuasted
        while (cur.next != null && steps > 0) {
            cur = cur.next;
            --steps;
        }
        return cur.url;
    }
}

1472. Design Browser History - Medium
https://f88083.github.io/2024/09/29/1472-Design-Browser-History-Medium/
作者
Simon Lai
發布於
2024年9月29日
許可協議