Skip to main content

Posts

Showing posts from June, 2014

Delete a node from doubly linked list

Deletion operation in DLL is simpler when compared to SLL. Because we don't have to go in search of previous node of to-be-deleted node.  Here is how you delete a node Link previous node of node of to-be-deleted to next node. Link next node of node of to-be-deleted to previous node. Free the memory of node of to-be-deleted Simple, isn't it. The code can go like this. prevnode = delnode->prev; nextnode = delnode->next; prevnode->next = nextnode; nextnode->prev = prevnode; free(delnode); And that is it. The node delnode is deleted. But we should always consider boundary conditions. What happens if we are trying to delete the first node or last node? If first node is to be deleted, its previous node is NULL. Hence step 3 should not be used.  And also, once head is deleted, nextnode becomes head . Similarly if last node is to be deleted, nextnode is NULL. Hence step 4 is as strict NO NO. And we should set prevnode to tail. After we put these things together, we have

Doubly Linked List

Doubly Linked List is a list where each node has two links - one to the next node and another to the previous node. Because of two links , operations on this list are considerably easie r . But t here is an overhead of one more pointer in each node. First we need to have a node for the list. As I mentioned earlier, the node will have data - in this case a simple integer and two pointers. struct node { int n; struct node * next; struct node * prev; }; typedef struct node * NODEPTR; We have type def ined NODEPTR as we will be use it often. Next we have to define two pointers - head of the list and tail of the list. And let us not forget to initialize them to NULL. int main () { NODEPTR head,tail; head = tail = NULL ; Our create_node function will be similar to that of singly linked list . Only difference is we have to initialize newnode->prev as well . To NULL. L et us write functions to insert a node to  list. Let us s

Insert a node into sorted list

A singly linked list is a data structure where each node is linked to the next node. In such a list, if you have to add a new node, it can be done in a simple way such as     find the last node     link last node to new node Which can be done using code such as NODEPTR insertnode(NODEPTR head, NODEPTR newnode) { if(head==NULL) { head = newnode; } else { NODEPTR temp = head; while(temp->next !=NULL)//till we have not reached last node { temp = temp->next; } // now temp is our last node. add new node after this temp->next = newnode; } But if we have a sorted list and we want to add a new node to this list we should traverse to first node temp which is greater than new node add the new node to previous node of this prev->next = newnode; newnode->next = temp; To find previous node, each time store current node in prev before moving to next node We also need to consider one special case,