Lecture 2 (Learn Doubly Linked List)¶
Create a Node¶
In [1]:
class Node:
def __init__(self,val=0,next=None,prev=None):
self.val = val
self.next = next
self.prev = prev
node = Node(100)
Convert a list into doubly linked list¶
In [3]:
def to_dll(nums):
if not nums:
return None
head = Node(nums[0])
temp = head
for num in nums[1:]:
temp.next = Node(num,prev=temp)
temp = temp.next
return head
Convert dll to list¶
In [4]:
def from_dll(head):
result = []
temp = head
while temp is not None:
result.append(temp.val)
temp = temp.next
return result
print(from_dll(to_dll([1,2,3,4,5])))
[1, 2, 3, 4, 5]
Insert at end of Doubly Linked List¶
Given a doubly linked list, and a value ‘k’, insert a node having value ‘k’ at the end of the doubly linked list.
DLL: 1 <-> 2 <-> 3 <-> 4
Value to be Inserted: 6
Result: DLL: 1 <-> 2 <-> 3 <-> 4 <-> 6
DLL: 10 <-> 20 <-> 30
Value to be Inserted: 40
Result: DLL: 10 <-> 20 <-> 30 <-> 40
Approach 1¶
- Reach till the end first
- insert the new node
In [5]:
def insert_end(dll,val):
if dll is None:
return Node(val)
temp = dll
while temp.next is not None:
temp = temp.next
temp.next = Node(val,prev=temp)
return dll
print(from_dll(insert_end(to_dll([1,2,3,4]),6)))
print(from_dll(insert_end(to_dll([10,20,30]),40)))
[1, 2, 3, 4, 6] [10, 20, 30, 40]
Complexity¶
O(N) : N = no. elements in dll
O(1)