Balancing in AVL tree only in main root - avl-tree

I am creating AVL binary tree in which the only problem is that the root is not changes its position or gets balance except all other child's root or leaves etc
Any help would be greatly appreciated!
Logical Layer file
public class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
public class BinaryTree
{
public Node root;
public BinaryTree()
{
root = null;
}
public int height(Node temp)
{
int h = 0;
if (temp != null)
{
int l_height = height(temp.left);
int r_height = height(temp.right);
int max_height = Math.Max(l_height, r_height);
h = max_height + 1;
}
return h;
}
public int diff(Node temp)
{
int l_height = height(temp.left);
int r_height = height(temp.right);
int b_factor = l_height - r_height;
return b_factor;
}
Node rr_rotation(Node parent)
{
Node temp;
temp = parent.right;
parent.right = temp.left;
temp.left = parent;
return temp;
}
Node ll_rotation(Node parent)
{
Node temp;
temp = parent.left;
parent.left = temp.right;
temp.right = parent;
return temp;
}
Node lr_rotation(Node parent)
{
Node temp;
temp = parent.left;
parent.left = rr_rotation(temp);
return ll_rotation(parent);
}
Node rl_rotation(Node parent)
{
Node temp;
temp = parent.right;
parent.right = ll_rotation(temp);
return rr_rotation(parent);
}
Node balance(Node temp)
{
int bal_factor = diff(temp);
if (bal_factor > 1)
{
if (diff(temp.left) > 0)
temp = ll_rotation(temp);
else
temp = lr_rotation(temp);
}
else if (bal_factor < -1)
{
if (diff(temp.right) > 0)
temp = rl_rotation(temp);
else
temp = rr_rotation(temp);
}
return temp;
}
public Node addNode(int data) // It only add the Root(that is 55 in the fig)
{
Node newNode = new Node(data);
if (root == null)
{
root = newNode;
}
return root;
}
public Node insertNode(Node root, int newNode) //But I want to make this should add root node.
{
if (root == null) (I think here is some problem)
{
root = new Node(newNode);
root.data = newNode;
root.left = null;
root.right = null;
return root;
}
if (newNode < root.data)
{
root.left = insertNode(root.left, newNode);
root = balance(root);
}
else if (newNode >= root.data)
{
root.right = insertNode(root.right, newNode);
root = balance(root);
}
return root;
}
}
Presentataion layer file
public partial class PresentationLayer : Form
{
BinaryTree obj = new BinaryTree();
int a, b;
public PresentationLayer()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) //add node button
{
int num = 0;
bool result = int.TryParse(textBox1.Text, out num);
if (result)
{
a = Int32.Parse(textBox1.Text);
obj.addNode(a); //It creates root
textBox1.Hide();
button1.Hide();
}
}
private void button2_Click_1(object sender, EventArgs e) //insert button
{
int num = 0;
bool result = int.TryParse(textBox2.Text, out num);
if (result)
{
b = Int32.Parse(textBox2.Text);
Node abc = new Node(b);
obj.insertNode(obj.root, b); //It is not creating root
textBox2.Clear();
}
}
}
}
Any help would be greatly appreciated!

You should add cases into the ll_rotation and rr_rotation functions to handle when the root is rotated. You should be able to check if the parameter parent is the same node as root, and if so, set root to refer to the new rotated node.
For example, per Wikipedia's example of left rotation:
P
/ \
/ \
A Q
/ \
B C
Rotates Left to become:
Q
/ \
/ \
P C
/ \
A B
If ll_rotation(P) is called where P is the same node as root, then the function should assign Q to be the new root

Related

Insert function for every binary tree

If i have for example 2 binary trees:
typedef struct node {
int key;
struct node *left, *right;
} node;
node* root1
node* root2
I've tried this function to insert nodes:
void insert(node* root, int key) {
node *p, *q;
p = (node*) calloc(1,sizeof(node);
p->key = key;
if (root == NULL) {
root = p;
return;
}
q = root;
for (;;) {
if (key < q->key) {
if (q->left == 0) {
q->left = p;
return;
} else q = q->left;
} else if (key > q->key) {
if (q->right == 0) {
q->right = p;
return;
} else q = q->right;
} else {
free(p);
return;
}
}
}
but after call insert(root1,10) the tree root1 remains untouched. I suppose it happens because root variable inside function is changed locally.
How i should implement the function that will receive as argument the tree in which i want to insert nodes?
You could always return a pointer to the root, like this
node* insert(node* root, int key) {
node *p, *q;
p = (node*) calloc(1,sizeof(node));
p->key = key;
if (root == NULL) {
root = p;
return root;
}
q = root;
for (;;) {
if (key < q->key) {
if (q->left == 0) {
q->left = p;
return root;
} else q = q->left;
} else if (key > q->key) {
if (q->right == 0) {
q->right = p;
return root;
} else q = q->right;
} else {
free(p);
return root;
}
}
}
And you create your tree like -
node* root1 = NULL;
root1 = insert(root1,3)

AVL Tree in C with iterative insertion

I'm coding a generic AVL tree as both a challenge to myself and, if I can do it properly, a resource for other CS students out there.
As one usually would, I started by implementing a recursive insertion function, which works. However, due to efficiency, I tried to implement the same function, but iteratively. I searched online and found lots of implementations, but the rest of the code was always too different from mine, which led me to continue attempting to create an implementation from scratch.
These are the relevant defined types:
typedef struct info {
int id;
char name[200];
} data;
typedef struct avl_node {
void * data;
struct avl_node * left;
struct avl_node * right;
int height;
} * avl_node_t;
typedef struct avl_tree {
avl_node_t root;
int num_nodes;
int (*less)(const void * first, const void * second);
int (*key)(const void * data);
} * avl_t;
And as follows is the iterative insertion function (which doesn't work as intended):
avl_node_t
avl_insert(avl_node_t node, void * data)
{
long key1 = 0, key2 = 0;
avl_node_t aux = NULL;
while (1) {
if (node == NULL) {
node = avl_node_create(data);
break;
}
key1 = key((void*)&data);
key2 = key((void*)&(node->data));
aux = node;
if (less((void*)&key1, (void*)&key2))
node = node->left;
else
node = node->right;
}
if (aux != NULL) {
if (less((void*)&key1, (void*)&key2))
aux->right = node;
else if (less((void*)&key2, (void*)&key1))
aux->left = node;
}
node = avl_balance(node);
return node;
}
In which the avl_balance function is defined as such:
static short
balance(avl_node_t node)
{
if (node == NULL)
return 0;
return avl_node_height(node->left) - avl_node_height(node->right);
}
static avl_node_t
avl_balance(avl_node_t node)
{
short balance_factor;
if (node == NULL)
return node;
balance_factor = balance(node);
if (balance_factor > 1)
if (balance(node->left) >= 0)
node = avl_rotRight(node);
else
node = avl_rotLeftRight(node);
else if (balance_factor < -1)
if (balance(node->right) <= 0)
node = avl_rotLeft(node);
else
node = avl_rotRightLeft(node);
else
update_height(node);
return node;
}
This is the code I'm using to test the AVL tree:
int main()
{
data d1 = { 1, "we are number one" };
data d2 = { 2, "boneless pizza" };
data d3 = { 3, "hehe" };
data d4 = { 4, "achoo" };
data d5 = { 5, "I like C" };
data d6 = { 6, "Assembly is cool too" };
data d7 = { 7, "SIGSEGV" };
avl_t tree = avl_create();
avl_node_t root = tree->root;
root = avl_insert(root, (void*)&d1);
traverse(root);
root = avl_insert(root, (void*)&d2);
traverse(root);
root = avl_insert(root, (void*)&d3);
root = avl_insert(root, (void*)&d4);
root = avl_insert(root, (void*)&d5);
root = avl_insert(root, (void*)&d6);
root = avl_insert(root, (void*)&d7);
traverse(root);
free(tree);
exit(0);
}
In which traverse is defined as such:
void visit(void * d)
{
data * my_data = (data*)d;
printf("I am element number %d named %s\n", (*my_data).id, (*my_data).name);
fflush(stdout);
}
void traverse(avl_node_t node)
{
if (node == NULL)
return;
traverse(node->left);
traverse(node->right);
visit(node->data);
}
And finally, this is the output I'm getting from this test:
I am element number 1 named we are number one
I am element number 2 named boneless pizza
I am element number 7 named SIGSEGV
Thank you in advance.
If you do not mind, i implemented it in c++ version.
// In the view of C, just omit the template declaration and replace the class with struct
template<typename T>
class AVL_tree{
private:
class AVL_Node{
public:
T val;
AVL_Node* left;
AVL_Node* right;
AVL_Node* parent;
int height;
// Node Constructor -
AVL_Node():left{nullptr}, right{nullptr}, parent{nullptr}, val{}, height{0}{}
AVL_Node(T val): left{nullptr}, right{nullptr}, parent{nullptr}, height{0}, val{val}{}
};
AVL_Node* root;
short (*cmp_func)(T, T);
// Utility -
void add_child(AVL_Node* prev_nd, AVL_Node* chd_nd){
if(prev_nd == nullptr){
this->root = chd_nd;
return;
}
// update parent pointer first.
switch(cmp_func(chd_nd->val, prev_nd->val)){
case 1:
prev_nd->right = chd_nd;
break;
case 0:
prev_nd->left = chd_nd;
break;
case -1:
cerr << "Warning : The element should not be duplicate." << endl;
return;
default:
cerr << "ERROR_MESSAGE : The self-defin compare func should return triple value (1, 0, -1)." << endl;
return;
}
// update parent pointer of child node
chd_nd->parent = prev_nd;
}
AVL_Node* find_node(T val){
AVL_Node* prev_ptr = nullptr;
for(AVL_Node* tmp_ptr = this->root ; tmp_ptr != nullptr ; ){
prev_ptr = tmp_ptr;
switch(cmp_func(val, tmp_ptr->val)){
case 1:
tmp_ptr = tmp_ptr->right;
break;
case 0:
tmp_ptr = tmp_ptr->left;
break;
case -1:
return prev_ptr;
}
}
// for not find the node, return their parent node.
return prev_ptr;
}
int get_max(int a, int b){ return (a >= b) ? a : b; }
int get_height(AVL_Node* ptr_nd){
if(ptr_nd == nullptr)
return -1;
return ptr_nd->height;
}
int cal_balance(AVL_Node* nd_ptr){ return get_height(nd_ptr->left) - get_height(nd_ptr->right); }
AVL_Node* Right_rotate(AVL_Node* curr_nd){
AVL_Node* lft_chd = curr_nd->left;
AVL_Node* rgt_suc = lft_chd->right;
// Perform rotation
lft_chd->right = curr_nd;
curr_nd->left = rgt_suc;
// update parent pointer of current pointed node and child node
lft_chd->parent = curr_nd->parent;
curr_nd->parent = lft_chd;
if(rgt_suc != nullptr)
rgt_suc->parent = curr_nd;
// Update heights
lft_chd->height = get_max(get_height(lft_chd->left), get_height(lft_chd->right)) + 1;
curr_nd->height = get_max(get_height(curr_nd->left), get_height(curr_nd->right)) + 1;
return lft_chd;
}
AVL_Node* Left_rotate(AVL_Node* curr_nd){
AVL_Node* rgt_chd = curr_nd->right;
AVL_Node* lft_suc = rgt_chd->left;
// Perform rotation
rgt_chd->left = curr_nd;
curr_nd->right = lft_suc;
// update parent pointer of current pointed node and child node
rgt_chd->parent = curr_nd->parent;
curr_nd->parent = rgt_chd;
if(lft_suc != nullptr)
lft_suc->parent = curr_nd;
// Update heights
rgt_chd->height = get_max(get_height(rgt_chd->left), get_height(rgt_chd->right)) + 1;
curr_nd->height = get_max(get_height(curr_nd->left), get_height(curr_nd->right)) + 1;
return rgt_chd;
}
void splice(AVL_Node* ptr_nd){
/* remove node confirm that the ptr_nd have successor in single side.
Case 1. ; Case 2. */
AVL_Node* succsor_nd = (ptr_nd->left != nullptr) ? ptr_nd->left : ptr_nd->right;
if(ptr_nd == this->root){ // for remove the root.
this->root = succsor_nd;
}else{
AVL_Node* par_nd = ptr_nd->parent;
if(par_nd->left == ptr_nd)
par_nd->left = succsor_nd;
else
par_nd->right = succsor_nd;
if(succsor_nd != nullptr) succsor_nd->parent = par_nd;
}
}
public:
enum Order{ // for the order traversal.
pre_order,
post_order,
in_order
};
// Constructor -
AVL_tree():root{nullptr}, cmp_func{&defau_cmp<T>}{}
AVL_tree(short (*def_cmp_func)(T, T)):root{nullptr}, cmp_func{def_cmp_func}{}
// Operation -
void insert(T val){
// BST insertion operation
AVL_Node* prev_nd = find_node(val);
AVL_Node* chd_nd = new AVL_Node(val);
add_child(prev_nd, chd_nd);
// Balance the tree
for(AVL_Node* nd_ptr = prev_nd ; nd_ptr != nullptr ; nd_ptr = nd_ptr->parent){
const int& bf = cal_balance(nd_ptr);
// Left bias unbalance
if( bf > 1 ){
if(val > nd_ptr->left->val)
nd_ptr->left = Left_rotate(nd_ptr->left);
// update parent's pointer
AVL_Node* par_ptr = nd_ptr->parent;
if(par_ptr != nullptr && par_ptr->right == nd_ptr)
par_ptr->right = Right_rotate(nd_ptr);
else if(par_ptr != nullptr && par_ptr->left == nd_ptr)
par_ptr->left = Right_rotate(nd_ptr);
else
Right_rotate(nd_ptr);
// Right bias unbalance
}else if(bf < -1){
if(val < nd_ptr->right->val)
nd_ptr->right = Right_rotate(nd_ptr->right);
// update parent's pointer
AVL_Node* par_ptr = nd_ptr->parent;
if(par_ptr != nullptr && par_ptr->right == nd_ptr)
par_ptr->right = Left_rotate(nd_ptr);
else if(par_ptr != nullptr && par_ptr->left == nd_ptr)
par_ptr->left = Left_rotate(nd_ptr);
else // nd_ptr equal root
Left_rotate(nd_ptr);
// else, the sub-tree is already balanced
}else{
nd_ptr->height = get_max(get_height(nd_ptr->left), get_height(nd_ptr->right)) + 1;
}
// finally update the new root pointer
if(nd_ptr->parent == nullptr)
this->root = nd_ptr;
}
}
// remove operation is still working on it though.
// Smart_queue just like a queue offer general interface, you can use stl-container.
void BF_print(){
Smart_queue<AVL_Node*> nd_que(this->root);
while(!nd_que.is_empty()){
AVL_Node* tmp_ptr = nd_que.pop();
if(tmp_ptr == nullptr)
continue;
cout << tmp_ptr->val << " ";
nd_que.push(tmp_ptr->left);
nd_que.push(tmp_ptr->right);
}
}
};

C malloc to pointer to NULL not working

I am writing a function that inserts a new node in a binary search tree. In order to avoid having too many if-else's, I am using a pointer called nodeSide that points to either node's left or right, as follows:
void insertHelper(Node *node, int val) {
Node *nodeSide;
if (val < node->val) {
nodeSide = node->left;
} else {
nodeSide = node->right;
}
if (nodeSide == NULL) {
nodeSide = (Node *)malloc(sizeof(Node));
nodeSide->val = val;
nodeSide->left = NULL;
nodeSide->right = NULL;
return;
}
else {
insertHelper(nodeSide, val);
}
}
The node however, isn't actually being added. It seems like doing this:
Node *node = malloc(...);
node->left = NULL;
Node *anotherNode = nodeLeft;
anotherNode = malloc(...);
doesn't in fact add a new node to tree. Any ideas why? The pointer should be pointing to the right place, regardless whether it is null or not. Or am I wrong here?
Here is my full code:
#include <stdlib.h>
#include <stdio.h>
typedef struct _node {
int val;
struct _node * left;
struct _node * right;
int ht;
} Node;
void insertHelper(Node *node, int val) {
Node *nodeSide;
if (val < node->val) {
nodeSide = node->left;
} else {
nodeSide = node->right;
}
if (nodeSide == NULL) {
nodeSide = (Node *)malloc(sizeof(Node));
nodeSide->val = val;
nodeSide->left = NULL;
nodeSide->right = NULL;
return;
}
else {
insertHelper(nodeSide, val);
}
}
Node * getNode(int value) {
Node * node = (Node * )malloc(sizeof(Node));
node->val = value;
node->left = NULL;
node->right = NULL;
node->ht = 0;
return node;
}
Node * getTree() {
Node *root = getNode(3);
Node *rootLeft = getNode(2);
root->left = rootLeft;
Node *rootRight = getNode(4);
root->right = rootRight;
Node *rootRightRight = getNode(5);
rootRight->right = rootRightRight;
return root;
}
int main() {
Node * root = getTree();
insertHelper(root, 6);
// to verify:
printf("%d", root->right->right->right->val);
return 0;
}
Your code does not store the new node that you create anywhere in your tree.
Perhaps you could do e.g.
if (nodeSide == NULL) {
nodeSide = (Node *)malloc(sizeof(Node));
nodeSide->val = val;
nodeSide->left = NULL;
nodeSide->right = NULL;
if (val < node->val)
node->left = nodeSide;
} else {
node->right = nodeSide;
}
return;
}
But you could use a double pointer, to avoid the extra if/else there:
Node **nodeSide;
if (val < node->val) {
nodeSide = &node->left;
} else {
nodeSide = &node->right;
}
if (*nodeSide == NULL) {
*nodeSide = (Node *)malloc(sizeof(Node));
(*nodeSide)->val = val;
(*nodeSide)->left = NULL;
(*nodeSide)->right = NULL;
return;
}
else {
insertHelper(*nodeSide, val);
}
}
Youre insertHelper seems to lack one relevant line of code just before the return:
node->left = nodeSide;
But keep in mind which side to add the value. Maybe you should track the relevant side as variable inside the function.

Iteratively inserting into a binary tree

I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
However, when I'm finding the height of this tree I am always getting 0. The height code is
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing?
Here:
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
You navigate the tree until you hit T == NULL. Then you create a node and assign the pointer to it to T. Then you return the original value of T. You don't modify your tree at all. No node in it is made to point to the newly created node. T is just a local variable.
Couldn't solve the problem that way. This code, however, seems to work.
BST Insert(int x, BST T)
{
BST temp=T;
BST node=(BST)malloc(sizeof(struct TreeNode));
node->Element=x;
node->Left=NULL;
node->Right=NULL;
if (T==NULL)
{
T=node;
return(T);
//printf("%d\n",T->Element);
}
else
{
while(1)
{
if (temp->Element>=node->Element && temp->Left==NULL)
{
temp->Left=node;
break;
}
else if (temp->Element>=node->Element && temp->Left!=NULL)
{
temp=temp->Left;
}
else if (temp->Element<node->Element && temp->Right==NULL)
{
temp->Right=node;
break;
}
else
{
temp=temp->Right;
}
}
return(T);
}
}
Here's My implementation of the aforementioned problem:
bst* newNode(int x)
{
bst* T = new bst;
T->value = x;
T->left_child = T->right_child = NULL;
return T;
}
bst* bst_insert_iter(bst* T,int val)
{
if (T == NULL)
T = newNode(val);
else
{
bst *temp_node = T;
bool flag = true;
while(flag)
{
if (val <= temp_node->value)
{
if (temp_node->left_child == NULL)
{
temp_node->left_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->left_child;
}
else
{
if (temp_node->right_child == NULL)
{
temp_node->right_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->right_child;
}
}
}
return T;
}
You have the bug in your insert function. As I may assume, initially your tree is empty. so the first time you insert a node, the second argument is NULL, right? Then this function always returns NULL to you as you always pass a NULL value.
template <class T>
class TreeNode{
private:
T data;
TreeNode<T>* right,*left;
public:
void setData(T d){
this->data =d;
}
T getData(){
return this->data;
}
void setRight(TreeNode<T>* r){
this->right =r;
}
TreeNode<T>* getRight(){
return this->right;
}
void setLeft(TreeNode<T>* r){
this->left =r;
}
TreeNode<T>* getLeft(){
return this->left;
}
static TreeNode<T>* newNode(T data){
TreeNode<T>* n = new TreeNode<T>();
n->setData(data);
n->setRight(NULL);
n->setLeft(NULL);
return n;
}
};
template <class T>
class BinaryTree{
private:
TreeNode<T>* root;
public:
void insert(T data){
TreeNode<T>* n = TreeNode<T>::newNode(data);
if(root==NULL)
root = n;
else{
TreeNode<T>* t = root;
while(t!=NULL){
if(n->getData() >= t->getData()){
if(t->getRight()==NULL){
t->setRight(n); //newnode attached as right child in tree
t = NULL;
}
else
t = t->getRight();
}
else{
if(t->getLeft()==NULL){
t->setLeft(n); //newnode attached as left child in tree
t=NULL;
}
else
t = t->getLeft();
}
}
}
}
void preorder(){
TreeNode<T>* t = root;
preorderUtil(t);
}
void preorderUtil(TreeNode<T>* node){
if(node==NULL)
return;
preorderUtil(node->getLeft());
cout<<node->getData()<<" ";
preorderUtil(node->getRight());
}
};
Your changes are not reflected in the tree. I followed this way to insert data iteratively and it works fine. The point is making a node inside your binarytree to point the newly created node such that it gets attached to the tree.
Here is my version , it seems to be working.
struct tree{
tree *left;
tree *right;
int key;
};
void insertBst(int k,tree *t)
{
tree *newK = new tree[sizeof(tree)];
newK->key = k;
newK->left = NULL;
newK->right = NULL;
if((t)->key == NULL)
{
t=newK;
return;
}
else{
bool found = false;
tree *root = t;
tree *parent = NULL;
while(root != NULL)
{
parent = root;
if(root->key < newK->key)
{
root=root->right;
}
else if(root->key > newK->key)
{
root=root->left;
}
else{
//Here we have duplicates!! so do nothing
root = root;
}
}
if(parent->key > newK->key) parent->left = newK;
else parent->right = newK;
}
}

Linked list insertion sort

I'm not very advanced in the sorting part of programming yet, so I was looking for some help with my algorithm.
void sortList()
{
Item_PTR tmpNxt = current->nextItem;
Item_PTR tmpPTR = current;
int a, tmp;
while(tmpNxt != NULL)
{
a = tmpPTR->value;
while(tmpNxt != tmpPTR && tmpNxt->value < a)
{
tmp = a;
tmpPTR->value = tmpNxt->value;
tmpNxt->value = tmp;
tmpPTR = tmpPTR->nextItem;
}
tmpPTR = current;
tmpNxt = tmpNxt->nextItem;
}
}
The list state before sorting: 9 8 7 6 5 4 3 2 1
after sorting: 1 9 8 7 6 5 4 3 2
I'm not sure why...I've played computer a lot on paper and I feel like it should work...but maybe other eyes will spot the problem.
Current is a global pointer that will always have the location of the first/ top element in the list.
In addition to the changes suggested by #Arun Saha, there seems to be some logical mistake (not updating a value after swapping), that's why the list os not even printing in sorted order even inside the sort function. Following code should solve that.
void sortList()
{
Item_PTR tmpNxt = current->nextItem;
Item_PTR tmpPTR = current;
while(tmpNxt != NULL)
{
while(tmpNxt != tmpPTR && tmpNxt->value < tmpPTR->value)
{
int tmp = tmpPTR->value;
tmpPTR->value = tmpNxt->value;
tmpNxt->value = tmp;
tmpPTR = tmpPTR->nextItem;
}
tmpPTR = current;
tmpNxt = tmpNxt->nextItem;
}
}
This is because the function sortList() is not changing current, the "global"
variable denoting the list head.
Please don't use a global variable, and certainly not for a linked list head. (What will you do when you need two lists?)
I would redesign the sortList() function to either one of the following:
/* sort the list pointed to by phead and return the new head after sorting */
Item_PTR sortList( Item_PTR phead );
/* sort the list pointed to by *pphead */
void sortList( Item_PTR * pphead );
Also, make yourself familiar (even if you can't use them in the immediate project) to the interface of C++ Standard Library for lists, std::list link
**Java code for insertion sort of linked list**
package LinkedList;
/**
* Created by dheeraj on 5/1/15.
*/
public class InsertionSortLinkedList {
private static final class Node {
int value;
Node next;
public Node(int d) {
value = d;
next = null;
}
}
private Node root;
private Node sortedHead;
private void addData(int data) {
if (root == null) {
root = new Node(data);
} else {
Node temp = new Node(data);
temp.next = root;
root = temp;
}
}
private void printList() {
Node temp = root;
while (temp != null) {
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}
private void printSortedList() {
Node temp = sortedHead;
while (temp != null) {
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}
private void insertionSort() {
Node outer = root;
Node resultRoot = null;
if (outer == null) {
return;
}
while (outer != null) {
if (resultRoot == null) {
//System.out.println("null");
resultRoot = new Node(outer.value);
} else {
Node t = resultRoot;
if (outer.value < t.value) {
//current outer is smallest
//System.out.println("smallest");
Node temp = new Node(outer.value);
temp.next = t;
resultRoot = temp;
} else {
boolean broken = false;
while (t.next != null) {
if (t.value < outer.value && outer.value <= t.next.value) {
Node temp = new Node(outer.value);
temp.next = t.next;
t.next = temp;
broken = true;
//System.out.println("middle");
break;
}
//
t = t.next;
}
if (!broken) {
//current outer is greatest
//System.out.println("largest");
t.next = new Node(outer.value);
}
}
}
outer = outer.next;
}
sortedHead = resultRoot;
}
public static void main(String[] args) {
InsertionSortLinkedList insertionSortLinkedList = new InsertionSortLinkedList();
insertionSortLinkedList.addData(5);
insertionSortLinkedList.addData(30);
insertionSortLinkedList.addData(1);
insertionSortLinkedList.addData(18);
insertionSortLinkedList.addData(19);
insertionSortLinkedList.printList();
insertionSortLinkedList.insertionSort();
insertionSortLinkedList.printSortedList();
}
}

Resources