linked list - progress update

This commit is contained in:
Artem Sergeev 2022-11-28 21:39:58 +02:00
parent 9fa2183a6a
commit a5a80b77f0
3 changed files with 65 additions and 3 deletions

View File

@ -660,8 +660,8 @@ if you can identify the runtime complexity of different algorithms. It's a super
- [x] push_back(value) - adds an item at the end
- [x] pop_back() - removes end item and returns its value
- [x] front() - get value of front item
- [ ] back() - get value of end item
- [ ] insert(index, value) - insert value at index, so current item at that index is pointed to by new item at index
- [x] back() - get value of end item
- [x] insert(index, value) - insert value at index, so current item at that index is pointed to by new item at index
- [ ] erase(index) - removes node at given index
- [ ] value_n_from_end(n) - returns the value of the node at nth position from the end of the list
- [x] reverse() - reverses the list

View File

@ -91,12 +91,49 @@ class LinkedList:
index -= 1
return node.get_value()
def insert(self, index, value):
if index > self.size() or index < 0:
raise IndexError(index)
if index == 0:
self.push_front(value)
return
if self.size() == 1 and index == 1:
self.push_back(value)
return
else:
cur_index = 0
node = self.__head
prev = node
while cur_index != index and node.get_next() is not None:
cur_index += 1
prev = node
node = node.get_next()
if cur_index != index:
raise IndexError(index)
else:
new_node = ListNode(value)
new_node.set_next(node)
prev.set_next(new_node)
self.__size += 1
def front(self):
"get value of front item"
"get value of the first item"
if self.size() == 0:
raise ListIsEmptyError
return self.__head.get_value()
def back(self):
"get value of the last item"
if self.size() == 0:
raise ListIsEmptyError
if self.size() == 1:
return self.__head.get_value()
else:
node = self.__head
while node.get_next() is not None:
node = node.get_next()
return node.get_value()
def reverse(self):
if self.size() == 0 or self.size() == 1:
pass
@ -108,3 +145,10 @@ class LinkedList:
node = node.get_next()
self.__head = reversed_list.__head
def print(self):
str = ""
node = self.__head
while node is not None:
str = f'{str} {node.get_value()}'
node = node.get_next()
return str.strip()

View File

@ -71,6 +71,24 @@ class LinkedListTestCase(unittest.TestCase):
value = linked_list.pop_front()
self.assertEqual(value, 3)
def test_should_get_back_item(self):
linked_list = LinkedList()
linked_list.push_front(1)
linked_list.push_front(2)
linked_list.push_front(3)
value = linked_list.back()
self.assertEqual(value, 1)
def test_insert(self):
linked_list = LinkedList()
linked_list.insert(0, 1)
linked_list.insert(1, 2)
linked_list.insert(1, 5)
output = "1 5 2"
printed = linked_list.print()
self.assertEqual(output, printed)
if __name__ == '__main__':
unittest.main()