Data Structure $ Algorithm Assignment: Group
Data Structure $ Algorithm Assignment: Group
head temp
600
400
400 600 800
6.Repeat Steps 4-8 if you want to add more nodes to the list.
The structure of creat nodes for a doubly linked list would be
defined as follows:
struct node{
charname[20];
node *nxt; // Pointer to next node
node *prv; // Pointer to previous node
};
node *current;
current = new node;
current->name = "Fred";
current->nxt = NULL;
current->prv = NULL;
We have also included some code to declare the first node and set its pointers to
NULL.
It gives the following situation:
3.3.2. Adding a Node to a Doubly Linked List
Adoubly linked list and insert a new node in beginning, end or at any position
in the list.
Steps to insert a new node in Doubly linked list
To insert a node at 3rd position.
1.Traverse to N-1 node in the list. Where N is the position
to insert. Say temp now points to N-1th node.
7. Final list
The structure of insert node a Doubly linked list
void add_node_at_start (string new_name)
{ // Declare a temporary pointer and move it to the start
node *temp = current;
while (temp->prv != NULL)
temp = temp->prv;
// Declare a new node and link it in
node *temp2;
temp2 = new node;
void add_node_at_end ()
{ // Declare a temporary pointer and move it to the end
node *temp = current;
while (temp->nxt != NULL)
temp = temp->nxt;
// Declare a new node and link it in
node *temp2;
temp2 = new node;
temp2->name = new_name; // Store the new name in the node
temp2->nxt = NULL; // This is the new start of the list
temp2->prv = temp; // Links to current list
temp->nxt = temp2;
}
Here, the new name is passed to the appropriate function as a parameter. We'll go through
the function for adding a node to the right-most end of the list. The method is similar for
adding a node at the other end. Firstly, a temporary pointer is set up and is made to march
along the list until it points to last node in the list.
After that, a new node is declared, and the name is copied into it. The nxt pointer of this
new node is set to NULL to indicate that this node will be the new end of the list.
The prv pointer of the new node is linked into the last node of the existing list.
The nxt pointer of the current end of the list is set to the new node.
3.3.3. Deleting a Node From a Doubly Linked List
Delete a node from beginning, end or at any position of the linked list.
Steps to delete node from any position of a doubly linked list
To delete node from 2nd position.
1. Traverse to Nth node of the linked list,lets say a
pointer current points to Nth node in our case 2 node.
2.Link the node behind current node with the node
ahead of current node, which means now the N-1th node
will point to N+1th node of the list. Which can be implemented
as current->prev->next = current->next