Showing posts from October, 2019

How to merge two sorted singly linked list

here we will discuss ,how to merge two sorted linked list such that the final list is sorted in ascending order the structure ( node ) definition is given below: typedef struct node{ int val; struct node* next; }* node; Explanation: we will insert (merge ) the elements of list 2 (f2) in f1 by comparing each nodes value. ALGORITHM: traverse both lists till one of them is completely traversed compare the values of node and if the value of node of list f1 is smaller then move to next node of f1 and increment the value of pos. the pos variable will be used after complete traversal to join the remaining elements of f2 if any. and if f2 nodes value is smaller then insert it before the current node in f1 and set f1 to previous node that is the node of f2 and increment f2 to next node. after completely traversing one of the lists , append the remaining elements of f2 if any in f1 . void merge_ll(node *first){ delete_ll(*first);*first=NULL; int pos=0; printf("

How to Reverse a Singly linked list ? C/C++ Program

To reverse a given linked list ,we have to point the next (link) of each node to its previous node(ie: the node which is pointing to it.) for that we will maintain three pointers : 1) prev : will point to the node which is pointing to the current node. 2) cur : will point to the node in which we have to change the next(link) to the previous node. 3) next: in the process of changing the cur->next to prev the           cur->next will be lost so to store the address of cur->next we use next pointer. Node definition: typedef struct node{ int val; struct node* next; }* node; as given above the node contains two members value and a pointer pointing to its own datatype which will store the address of another node . reverse_ll(node *first) : function : void reverse_ll(node* first){ node prev=NULL; node cur=(*first); node next=NULL; while(cur){ next=cur->next; cur->next=prev; prev=cur; cur=next; }