Inserting node at start in the SLL (Steps):
- Create New Node
- Fill Data into “Data Field“
- Make it’s “Pointer” or “Next Field” as NULL
- Node is to be inserted at Last Position so we need to traverse SLL upto Last Node.
- Make link between last node and newnode
void insert_at_end() { struct node *new_node,*current; new_node=(struct node *)malloc(sizeof(struct node)); if(new_node == NULL) printf("nFailed to Allocate Memory"); printf("nEnter the data : "); scanf("%d",&new_node->data); new_node->next=NULL; if(start==NULL) { start=new_node; current=new_node; } else { temp = start; while(temp->next!=NULL) { temp = temp->next; } temp->next = new_node; } }
Diagram :
Attention :
Attention :
- If starting node is not available then “Start = NULL” then following part is executed
if(start==NULL) { start=new_node; current=new_node; }
- If we have previously created First or starting node then “else part” will be executed to insert node at start
- Traverse Upto Last Node., So that temp can keep track of Last node
else { temp = start; while(temp->next!=NULL) { temp = temp->next; }
- Make Link between Newly Created node and Last node ( temp )
temp->next = new_node;
To pass Node Variable to Function Write it as –
void insert_at_end(struct node *temp)
No comments:
Post a Comment