Linear Data Structure 507
Insert an element at starting: 3
Linked list elements are: 3 9 5 1 2 3 4
Explanation The creation of a linked list is same as explained in the previous program. Here, an
element is inserted at the beginning. The function void atbeg () performs this task. In this function
two pointers *node (local to this function) and *t are declared. The m alloc () function allocates
memory to pointer node. The entered element is placed in the newly created node. Consider the
following statements.
t=first;
header=node;
header - >next=t;
first=header;
The above four statements adjust the pointer links.
t=first: This statement assigns contents of first to pointer t. This is essential because the newly created
node will become first. Hence, before changing pointer first, it is assigned to pointer t.
Header=node: We know that header always points to the first node. The newly created node which
is to be inserted at starting is assigned to the pointer header.
header->next=t: The pointer t holds the address of the first element ( before insertion). After insertion,
it will be second. The address of the second node is assigned to the first. The pointer header holds
the address of the first node and pointer t holds the address of the second element. Thus, these two
successive elements are linked by this statement.
first=header: Before execution of this statement, the first node points to the second node. If we
remove this statement, then only one element can be inserted. If we try to insert the second element,
i
t will replace the first element. After assignment of the address of header to first, the insertion can
be carried out successfully.
Insertion of the Node at the End
A new element is inserted or appended at the end of the existing linked list. The address of the
newly created node is linked to the previous node that is NULL. The new node link field is assigned
a NULL value. Fig. 14.20 explains the insertion operation.
(b) After insertion
Fig. 14.20 Insertion of an element at the end