The singly linked list is a linear data structure in which each element of the list contains a pointer which points to the next element in the list. Each element in the singly linked list is called a node. Each node has two components: data and a pointer next which points to the next node in the list
method | Time complexity | Space complexity |
---|---|---|
insert method | O(1) | O(1) |
include method | O(n) | O(1) |
toString method | O(n) | O(n) |
create 3 methods
complexity:
for the 3 methods the time complexityO(n), cause the code is running n times based on the linked list size and the position where you want to add
and the space complexity is O(1), cause we are reassigning the values and adding one node only every times it runs
initial linked list :head -> [1] -> [3] -> [2] -> X
append:
input : 5
output: head -> [1] -> [3] -> [2] -> [5] -> X
insertBefore:
input:3, 5
output: head -> [1] -> [5] -> [3] -> [2] -> X
insertAfter:
input: 3, 5
output : head -> [1] -> [3] -> [5] -> [2] -> X
create a method that takes an integer (k) as an argument and return the value of the nodes k’th place from the tail
time complexity : O(n), cause here we have two arrays which are not nested the first on will run n times based on the length of the linked list and the second one will run n times based on the valued passed so its O(n+n) = O(n) space complexity: O(1) , cause we are not storing variables more than once , and only reassigning
verification: linked list: { 10 } -> { 6 } -> { 22 } -> { 34 } -> { 5 } -> { 10 } -> { 20 } -> NULL
Input : 3
output : 34
input: 8
output: the number passed is bigger than the linked list
create a function that takes in Arguments: 2 linked lists and Return: Linked List, Zip the two linked lists together into one so that the nodes alternate between the two lists and return a reference to the head of the zipped list.
Complexity:
time complexity:O(n)
space Complexity: O(n)
verification:
input:(list1,list2)
list1:head -> [1] -> [3] -> [2] -> X
list2:head -> [5] -> [9] -> [4] -> X
output: head -> [1] -> [5] -> [3] -> [9] -> [2] -> [4] -> X