sorting the linked lists by modifying the links

痴心易碎 提交于 2019-12-23 06:06:11

问题


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;
    }
}

回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/21583918/sorting-the-linked-lists-by-modifying-the-links

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!