Linked List using C++ part5
Submitted by moazkhan on Saturday, August 16, 2014 - 23:58.
Linked List using C++ part5
In this tutorial, you will learn 1. Code of adding a node in middle of an ordered linked list. 2. Code for deleting a node in the middle of linked list. What is the code for adding a node in any location in ordered linked list? If you have read the previous tutorial, you already know that an ordered linked list is one in which data is arranged in ascending order. So when you add data in such a list, it must not distort the ascending order of list. Hence, you cannot add data anywhere in the list. Given below is the code for inserting node in linked list.- void insert_order (int val)
- {
- if(checkempty())
- {
- InsertAtStart(val);
- return;
- }
- Node *new_node;
- new_node= new Node;
- new_node->data=val;
- Node *prev, *cur;
- prev=NULL;
- cur=head;
- if(val<head->data)
- {
- new_node->next=head;
- head=new_node;
- cout<<"\tNumber Inserted: "<<val<<endl;
- return;
- }
- else
- {while(cur!=NULL && val>cur->data)
- {
- prev=cur;
- cur=cur->next;
- }
- new_node->next=cur;
- prev->next=new_node;
- }
- }
- void delete_order(int val)
- {
- Node *cur;
- cur=head;
- if (checkempty())
- {
- cout<<"Already empty"<<endl;
- }
- else if(head->data==val)
- {
- head=head->next;
- delete cur;
- cur=NULL;
- return;
- }
- else {while(cur->next!=NULL)
- {
- if(cur->next->data==val)
- {
- Node *d;
- d=cur->next;
- cur->next=cur->next->next;
- cout<<"\tNumber Deleted: "<<val<<endl;
- delete d;
- return;
- }
- cur=cur->next;
- }
- }
- cout<<" Number not found in the LIST\n";
- }
Add new comment
- 175 views