注册 登录
编程论坛 C++教室

链表相邻元素排序问题,程序能跑,但结果出错,对于一个指定链表排序时,经过排序只能得到首元素和最小元素,不知道哪里出了问题,请知道的教授一下

wengbin 发布于 2015-11-25 11:55, 599 次点击
程序代码:

typedef struct Queue_H
{
    int X;
    Queue_H* next;
}Queue_H;

程序代码:

Queue_H* Q_Que(Queue_H *head)
{
    Queue_H *p=head;
    do
    {
        if((p->X)<(p->next->X))
        {
            Queue_H* temp1,*temp2,*temp3;
            temp1=p;
            temp2=p->next;
            temp3=p->next->next;
            p=temp2;
            p->next=temp1;
            p->next->next=temp3;
        }
        p=p->next;
    }while(p!=NULL);
    return head;
}


[此贴子已经被作者于2015-11-25 11:57编辑过]

2 回复
#2
yangfrancis2015-11-26 20:46
//以下代码已测试
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Queue
{
    int x;
    Queue*next;
};
void Swap(int &a,int &b)
{
    int temp;temp=a;a=b;b=temp;
}
void Descend(Queue*h)//引入头指针
{
    Queue*last;last=NULL;
    Queue*p;
    do
    {
       p=h;
       while(p->next!=last)
       {
             if(p->x<p->next->x)
               Swap(p->x,p->next->x);
            p=p->next;
       }
       last=p;
    }while(h->next!=last);   
}
Queue*head;
int main()
{
    cout<<"请输入整数存入链表,以-10000结束输入。\n";
    int get;
    Queue*p_new;Queue*p;p=head;
    while(true)
    {
        cin>>get;
        if(get==-10000) break;
        else
        {
            p_new=new Queue;
            p_new->x=get;p_new->next=NULL;
            if(p==NULL)
            {
                p=p_new;head=p;
            }
            else
            {
                p->next=p_new;p=p->next;
            }
        }
    };
    cout<<"原始顺序:\n";
    p=head;
    while(p!=NULL)
    {
        cout<<p->x<<endl;p=p->next;
    }
    p=head;
    cout<<"新顺序:\n";
    Descend(head);
    while(p!=NULL)
    {
        cout<<p->x<<endl;p=p->next;
    }
    system("pause");
    return 0;
}
//代码有点长,只看Descend函数就行了,Swap是将两数置换,其他都只是输入
1