Lecture 1 : (Learn 1D Linked List)¶
Creating a linked list node¶
In [2]:
class Node:
def __init__(self,val=0,next=None):
self.val = val
self.next = next
node = Node(100)
print(node.val)
print(node.next)
100 None
Convert list to linked list¶
In [3]:
def to_linked_list(nums):
if not nums:
return None
head = Node(nums[0])
temp = head
for num in nums[1:]:
temp.next = Node(num)
temp = temp.next
return head
to_linked_list([1,2,3,4,5])
Out[3]:
<__main__.Node at 0x107eb69d0>
Print 1D linked list¶
In [4]:
def from_linked_list(head):
result = []
temp = head
while temp is not None:
result.append(temp.val)
temp = temp.next
return result
ll = to_linked_list([1,2,3,4,5])
print(from_linked_list(ll))
[1, 2, 3, 4, 5]
Insert at the head of a Linked List¶
Given a linked list and an integer value val, insert a new node with that value at the beginning (before the head) of the list and return the updated linked list.
Input Format: 0->1->2, val = 5
Result: 5->0->1->2
Input Format:12->5->8->7, val = 100
Result: 100->12->5->8->7
In [5]:
def insert_beg(ll,val):
return Node(val,ll)
print(from_linked_list(insert_beg(to_linked_list([0,1,2]),5)))
print(from_linked_list(insert_beg(to_linked_list([12,5,8,7]),100)))
[5, 0, 1, 2] [100, 12, 5, 8, 7]
Complexity¶
O(1)
O(1)
Length of linked list¶
Given the head of a linked list, print the length of the linked list.
Input Format: 0->1->2
Result =3
Input Format: 2->5->8->7
Result: 4
Approach 1 (Brute Force)¶
- linear traversal and keep track of count
In [6]:
def linked_list_length(head):
count = 0
temp = head
while temp is not None:
count +=1
temp = temp.next
return count
print(linked_list_length(to_linked_list([0,1,2])))
print(linked_list_length(to_linked_list([2,5,8,7])))
3 4
Complexity¶
O(N) : N = number of elements in the linked list
O(1)
Approach 2 (Using Recursion)¶
- length(None) = 0
- length(node) = 1 + length(node.next)
In [21]:
def linked_list_length(head):
if head is None:
return 0
return 1 + linked_list_length(head.next)
print(linked_list_length(to_linked_list([0,1,2])))
print(linked_list_length(to_linked_list([2,5,8,7])))
3 4
Complexity¶
O(N) : N = number of elements in LL
O(N) : N = number of elements in LL
Search an element in a Linked List¶
Given the head of a linked list and an integer value, find out whether the integer is present in the linked list or not. Return true if it is present, or else return false.
Input Format: 0->1->2, val = 2
Result True
Input Format: 12->5->8->7, val = 6
Result False
Approach 1 (Using Linear Search)¶
In [7]:
def check_val(head,val):
temp = head
while temp is not None:
if temp.val == val:
return True
temp = temp.next
return False
print(check_val(to_linked_list([0,1,2]),2) )
print(check_val(to_linked_list([12,5,8,7]),6) )
True False
Complexity¶
O(N) : N = number of elements in linked list
O(1)