136
Insertion in singly linked list at beginning
Inserting a new element into a singly linked list at beginning is quite simple. We just need to make a few adjustments in the node links. There are the following steps which need to be followed in order to inser a new node in the list at beginning.
- Allocate the space for the new node and store data into the data part of the node. This will be done by the following statements.
- Make the link part of the new node pointing to the existing first node of the list. This will be done by using the following statement.
- At the last, we need to make the new node as the first node of the list this will be done by using the following statement.
Algorithm
- Step 1: IF PTR = NULL
- Step 2: SET NEW_NODE = PTR
- Step 3: SET PTR = PTR → NEXT
- Step 4: SET NEW_NODE → DATA = VAL
- Step 5: SET NEW_NODE → NEXT = HEAD
- Step 6: SET HEAD = NEW_NODE
- Step 7: EXIT
Write OVERFLOW
Go to Step 7
[END OF IF]
C Function
Output
Enter the item which you want to insert? 12 Node inserted Press 0 to insert more ? 0 Enter the item which you want to insert? 23 Node inserted Press 0 to insert more ? 2
Next Topic#