0

i'm trying to sort the linked list by modifying the links not swapping the data.i'm using selection sort.i don't know where i am going wrong.i'm beginner please help me.

struct node
{
    int   data;
    node* link;
};

node* p;    

void sort()
{
    node* temp = p;
    node* save;
    node* prev;
    node* tprev;
    node* push = new node;

    tprev = NULL;
    for (; temp != NULL; temp = temp->link)
    {
        push = temp->link;
        for (; push != NULL; push = push->link)
        {
            if (push->data<temp->data)
            {
                save->link  = temp->link;
                temp->link  = push->link;
                push->link  = save->link;
                prev->link  = temp;
                tprev->link = push;
            }

            prev = push;
        }

        tprev = temp;
    }
}
25
  • 1
    Can you please consistently format the code, this looks bad. Clean code, is the first step to working code. Also, place spaces between operators. Commented Feb 5, 2014 at 17:16
  • i'm extremely i'm new-bie here i don't know how to format it would be helpful if you say how i can do Commented Feb 5, 2014 at 17:18
  • 1
    @saimadan your swapping nodes logic( code) is not correct you don't consider parent node's link. Read Swap nodes in a singly-linked list Commented Feb 5, 2014 at 17:21
  • 1
    @saimadan I wish I could answer But there is sorting logic also I posted my comment just regarding node swapping I learn How to correctly swap code you can read my answer I have linked. Commented Feb 5, 2014 at 17:30
  • 1
    @saimadan Ok I don't promise, but let me try to correct. Commented Feb 5, 2014 at 18:01

1 Answer 1

2
void sort(){
    node *temp, *push;
    node *tprev, *pprev;
    node *save;

    tprev = NULL;
    for (temp = p; temp != NULL; temp = temp->link){
        pprev = temp;
        for (push=temp->link; push != NULL; push = push->link){
            if (push->data < temp->data){
                save = temp->link;
                temp->link = push->link;
                if(save == push)
                    push->link = temp;
                else
                    push->link = save;
                if(pprev != temp)
                    pprev->link = temp;
                if(tprev)
                    tprev->link = push;
                else
                    p = push;
                save = temp;
                temp = push;
                push = save;
            }
            pprev = push;
        }
        tprev = temp;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.