1.97k likes | 5.6k Views
Singly Linked List. BTECH , EE KAZIRANGA UNIVERSITY. Singly Linked List. A Singly Linked List is one in which all nodes are linked together in some sequential manner. A Singly Linked List is a Dynamic data structure. It can grow and shrink depending on the operations performed on it. START.
E N D
Singly Linked List BTECH , EE KAZIRANGA UNIVERSITY
Singly Linked List • A Singly Linked List is one in which all nodes are linked together in some sequential manner. • A Singly Linked List is a Dynamic data structure. It can grow and shrink depending on the operations performed on it. START
Syntax of Node struct Node { int num; struct node *ptr; //Pointer to Node }
INSERTION in Singly Linked List Inserting a Node at the beginning Void insert_begin( int item ) { node *ptr; ptr = (node *)malloc(sizeof(node)); ptr -> info = item; if(start == NULL) { ptr->next = NULL; } else { ptr->next = start; } start = ptr; }
Inserting a Node at the end Void insert_end( int item ) { node *ptr, *loc; ptr = (node *)malloc(sizeof(node)); ptr -> info = item; ptr -> next = NULL; if(start == NULL) { start = ptr; } else { loc=start; while(loc->next != NULL) { loc = loc->next; } loc-next=ptr; } }
Inserting a Node at the specified position Void insert_spe( NODE *start, intitem ) { node *ptr, *temp; int loc, k; if(start==NULL) { printf(“Empty List”); return; } for(k=1, temp=start ; k<loc ; k++) { temp=temp->next; if(temp==NULL) { printf(“Node in List is less than the location”); return; } } ptr = (node *)malloc(sizeof(node)); ptr -> info = item; ptr -> next = temp->next; temp->next = ptr; }
DELETION in Singly Linked List Deletion of the First Node void delete_begin() { node *ptr; if(start == NULL) { printf(“Empty List”); return; } else { ptr=start; start=start->next; printf(“Element deleted is : %d”,ptr->num); free(ptr); } }
Deletion of the Last Node void delete_end() { node *ptr, *loc; if(start == NULL) { printf(“Empty List”); return; } else if(start->next==NULL) { ptr=start; start=NULL; printf(“Element Deleted : %d”,ptr->num); free(ptr); } else { loc=start; ptr=start->next; while(ptr->next != NULL) { loc=ptr; ptr=ptr->next; } loc->next=NULL; printf(“Element Deleted : %d”,ptr->num); free(ptr); } }
Deletion of the Node at a specified position void delete_specific() { node *ptr, *temp; Inti,loc; printf(“Enter the position where the node is to be deleted : ”); scanf(“%d”,&loc); if(start == NULL) { printf(“Empty List”); return; } else { ptr=start; for(i=1;i<=loc;i++) { temp = ptr; ptr = ptr -> next; if(ptr==NULL) { printf(“Node in List is less than the location”); return; } } printf(“Number deleted is : %d”, ptr->num ); temp->next=ptr->next; free(ptr); } }
ADVANTAGES AND DISADVANTAGES Advantages • Accessing of a node in the forward direction is easier. • Insertion and Deletion of nodes are easier Disadvantages • Accessing the preceding node of a current node is not possible as there is no backward traversal. • Accessing a node is time consuming