This class designs the operations of a browser history It works by using a doubly linked list to hold the urls with optimized navigation using step counters and memory management
| 12 | |
| 13 | |
| 14 | class BrowserHistory: |
| 15 | """ |
| 16 | This class designs the operations of a browser history |
| 17 | |
| 18 | It works by using a doubly linked list to hold the urls with optimized |
| 19 | navigation using step counters and memory management |
| 20 | """ |
| 21 | |
| 22 | def __init__(self, homepage: str): |
| 23 | """ |
| 24 | Returns - None |
| 25 | Input - str |
| 26 | ---------- |
| 27 | - Initialize doubly linked list which will serve as the |
| 28 | browser history and sets the current page |
| 29 | - Initialize navigation counters |
| 30 | """ |
| 31 | self._head = DLL(homepage) |
| 32 | self._curr = self._head |
| 33 | self._back_count = 0 |
| 34 | self._forward_count = 0 |
| 35 | |
| 36 | def visit(self, url: str) -> None: |
| 37 | """ |
| 38 | Returns - None |
| 39 | Input - str |
| 40 | ---------- |
| 41 | - Adds the current url to the DLL |
| 42 | - Sets both the next and previous values |
| 43 | - Cleans up forward history to prevent memory leaks |
| 44 | - Resets forward count and increments back count |
| 45 | """ |
| 46 | # Clear forward history to prevent memory leaks |
| 47 | self._curr.nxt = None |
| 48 | self._forward_count = 0 |
| 49 | |
| 50 | # Create and link new node |
| 51 | url_node = DLL(url) |
| 52 | self._curr.nxt = url_node |
| 53 | url_node.prev = self._curr |
| 54 | |
| 55 | # Update current node and counts |
| 56 | self._curr = url_node |
| 57 | self._back_count += 1 |
| 58 | |
| 59 | def back(self, steps: int) -> str: |
| 60 | """ |
| 61 | Returns - str |
| 62 | Input - int |
| 63 | ---------- |
| 64 | - Moves backwards through history up to available steps |
| 65 | - Updates navigation counters |
| 66 | - Returns current page URL |
| 67 | """ |
| 68 | # Only traverse available nodes |
| 69 | steps = min(steps, self._back_count) |
| 70 | while steps > 0: |
| 71 | self._curr = self._curr.prev |
no outgoing calls