Page 114 - DCAP407_DATA_STRUCTURE
P. 114
Unit 6: Linked List Operations
3. The function createlist() allocates the memory for list node and stores the
elements entered by the user.
4. The function add_beginning() allocates the memory for each element entered
by the user and stores the elements at the beginning of the list.
5. The function add_after() prompts the user to enter the input for the element
data and the position number where the data is to be stored.
6. The for statement in the add_after() function searches for the position to
insert the new element.
7. If the user enters a position that is less than the actual elements, then a
message saying “there are less elements present than the entered position
number” is displayed.
8. The Display() function displays the element data and the position where the
data is inserted.
9. The program terminates when the user enters 5.
In a doubly-linked list, the HEAD node is set to NULL. Suppose, you want to create a
node with a value of 20, then the head will now point to HEAD->next = new_node and
the new node will point to newnode->previous=HEAD. This depicts how two pointers
can be used to point to next and previous elements. Now, if you wish to add another
node with a value 30, then the node having the value 20 will become the head node.
You can create the second node by setting HEAD->next! =NULL and HEAD=HEAD-
>next.
Write a program to insert a node at the beginning of a doubly-linked list.
6.3.3 Inserting a Node in a Circular Linked List
Let us consider num as the data entered by the user, tmp as the temporary variable holding the address
of the first node and last as the last node in the list.
Algorithm to insert a new node after a given node is as follows:
1. Input the data
2. Call the getnode() function. The getnode() allocates the memory for the first node.
3. Save the node data in the tmp variable
4. Assign the data entered by the user to the data file of the tmp
5. If last node is equal to NULL, then assign the data present in tmp to last node. Otherwise, assign
address of last node to the address of tmp. Now, the tmp holds the address of last node.
6. Return the value present in last node
7. Exit.
LOVELY PROFESSIONAL UNIVERSITY 107