Skip to content

Instantly share code, notes, and snippets.

@lgp171188
Created July 13, 2013 07:55
Show Gist options
  • Save lgp171188/27a04dab3dc33679cdfe to your computer and use it in GitHub Desktop.
Save lgp171188/27a04dab3dc33679cdfe to your computer and use it in GitHub Desktop.
Linked list operations using double pointers
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
}*root_node;
bool compare(node* new_node, node* existing_node)
{
if (existing_node->data > new_node->data)
return false;
return true;
}
bool compare_delete(int data, node* existing_node)
{
if(existing_node->data == data)
return false;
return true;
}
void DeleteSortedNode(int data)
{
node **pp_node = &root_node; // Double pointer pp_node is always
// pointing to the pointer to a node.
// In the beginning it is pointing
// to head which is pointing to the
// first node. In the subsequent iterations
// it is pointing to the 'next' pointer
// of a node which is pointing to the
// next node, which allows checking the
// next node from the current node.
while(*pp_node != NULL && compare_delete(data, *pp_node))
{
pp_node = &(*pp_node)->next;
}
node *temp = *pp_node;
*pp_node = (*pp_node)->next;
delete(temp);
}
void AddSortedNode(node* new_node, bool debug=false)
{
node** pp_node = &root_node;
while(*pp_node != NULL && compare(new_node,*pp_node))
{
pp_node = &(*pp_node)->next;
}
new_node->next = *pp_node;
*pp_node = new_node;
}
void print_list()
{
node* temp_node = root_node;
while(temp_node != NULL)
{
cout<<temp_node->data<<" ";
temp_node = temp_node->next;
}
cout<<endl;
}
int main()
{
node* temp = new node();
temp->data = 1;
temp->next = NULL;
AddSortedNode(temp);
temp = new node();
temp->data = 2;
temp->next = NULL;
AddSortedNode(temp);
temp = new node();
temp->data = 3;
temp->next = NULL;
AddSortedNode(temp);
temp = new node();
temp->data = 4;
temp->next = NULL;
AddSortedNode(temp);
temp = new node();
temp->data = 6;
temp->next = NULL;
AddSortedNode(temp);
temp = new node();
temp->data = 7;
temp->next = NULL;
AddSortedNode(temp);
print_list();
temp = new node();
temp->data = 5;
temp->next = NULL;
AddSortedNode(temp, true);
print_list();
DeleteSortedNode(4);
print_list();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment