added a extra tail pointer to make appending faster without traversing the entire linked list
Closed this issue · 1 comments
PrabhuKiran8790 commented
This is my first time writing something here on GitHub.
I have added an extra tail pointer so that appending can be done faster in constant time.
but I don't have any idea on how to make a pull request.
PrabhuKiran8790 commented
Changes in the __init__
method
def __init__(self,
items: Optional[Sequence] = None,
first: Optional[_Node] = None,
tail: Optional[_Node] = None) -> None: # tail pointer
self._first = first
self._tail = tail
self._length = 0
if items:
for item in items:
self.append(item)
changes in the append
method
def append(self, item: Any) -> None:
if isinstance(item, list):
self._append_list(item)
return
if self._tail is None:
self.add_first(item)
return
new_node = _Node(item)
self._tail.next = new_node
self._tail = new_node
self._length += 1
def _append_list(self, item):
for e in item:
self.append(e)
no need to traverse the entire linked list. we can add the item at the end of the linked list in O(1)
time.
new add_first
method
def add_first(self, item: Any):
new_node = _Node(item)
new_node.next = self._first
self._first = new_node
if self._tail is None:
self._tail = self._first
self._length += 1
also added a new method that takes a list and adds the elements of the list to the existing linked list.
previously, using the append
method, if we try to add the list, the entire list is itself a new item in the linked list.
ll = LinkedList([1, 2, 3, 4, 5, 6])
ll.append([-1, -2, -3])
print(ll)
and the output is something like this
[1 -> 2 -> 3 -> 4 -> 5 -> 6 -> [-1, -2, -3]]
with the changes, I proposed, the output is
[1 -> 2 -> 3 -> 4 -> 5 -> 6 -> -1 -> -2 -> -3]