알고리즘/test

Linked List - leetcode 예시로 이해

이경찬 :) 2023. 3. 3. 15:13

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

 

Design Browser History - LeetCode

Can you solve this real interview question? Design Browser History - You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implem

leetcode.com

class ListNOde(object):
	def __init__(self, val=0, next=None, prev=None):
    		self.val = val
			self.next = next
        	self.prev = prev
class BrowserHistory(object):
	def __init__(self, homepage):
    		self.head = self.current = ListNode(val=homepage)
	def visit(self,url):
    		self.current.next = ListNode(val=url, prev=self.current)
        	self.current = self.current.next
        	return None
    def back(self, steps):
    		while steps > 0 and self.current.prev != None:
        		steps -= 1
            	self.current = self.current.prev
        	return self.current.val
    def forward(self, steps):
    		while steps > 0 and self.current.next != None:
        		steps -= 1
            	self.current = self.current.next
        	return self.current.val

INPUT

["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]

OUTPUT

[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]

클래식한 linked list의 좋은 문제였다.

내부동작

1.BrowserHistory("leetcode.com") 

homepage: leetcode.com

current : leetcode.com

head: leetcode.com

2.visit("goole.com")

val : google.com

prev : current(즉, leetcode.com)

current.next: google.com

3.back

받은 steps을 0이 되거나 prev가 None될 때(맨앞으로 와서 더이상 앞이 없을때)까지 while문 self.current 를 current.prev(한칸 앞으로 간다.)

4.forward

back과 과정은 같지만 앞으로간다.