首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问个单向链表的排序有关问题。小妹

2012-03-25 
请教个单向链表的排序问题。。。。小妹To All:大家好。如题。1.创建个单项链表。2.用冒泡实现排序。3.能够输出正确

请教个单向链表的排序问题。。。。小妹
To All:
  大家好。如题。
1.创建个单项链表。
2.用冒泡实现排序。
3.能够输出正确结果。

小妹的代码如下:

C/C++ code
struct Node{    int data;    Node* next;};Node *CreatList(Node*head)//创建链表  输入-999结束{    Node *p;    Node *tail;    int data;    cin>>data;    while(data!=-999)    {             if(head!=NULL)         {             tail = head;             while(tail->next!=NULL)             {                 tail = tail->next;             }         }         p = new Node();         p->data=data;         p->next = NULL;        if(head==NULL)       {            head = p;            tail = p;       }        else       {              tail->next = p;            tail = p;       }        cin>>data;    }    return head;}/*冒泡排序*/Node *BubbleSort(Node *head){    if( NULL == head->next)   {        return head;   }    else   {        Node *temp = new Node();        temp->data = 99;        temp->next = head;        head = temp;        Node *tail = NULL;        Node *p = NULL;        Node *q = NULL;        Node *r = NULL;        while(tail != head->next)        {            p = head;            q = head->next;            r = q->next;            while(tail != r)           {               if(q->data > r->data)              {                  p->next = q->next;                  q->next = r->next;                  r->next = q;                  p = r;                  r = q->next;              }               else              {                  p = q;                  q = r;                  r = r->next;              }                       }           tail = q;                }        head = head->next;        delete temp;   }    return head;}/显示函数void Display(Node* head){    Node* temp;    temp = head;    while(temp!=NULL)    {        cout<<temp->data<<endl;        temp = temp->next;    }}main.cppint _tmain(int argc, _TCHAR* argv[]){    Node *head = NULL;    head = CreatList(head);    //BubbleSort(head);//[color=#FF0000]①为什么这种方法调用,函数不能将整个链表返回[/color]           head = BubbleSort(head); //这种方法能将head返回        Display(head);    cout<<"aaa"<<endl;    getchar();    return 0;}




Q:请大家帮小妹解释下为什么①BubbleSort(head)不对?
谢谢

[解决办法]
为什么用head = BubbleSort(head);是正确的。
然儿用BubbleSort(head);错误。


head = BubbleSort(head);
在这个语句中,BubbleSort括号中的head只是main中head的一个copy,经过
BubbleSort后,把BubbleSort中head的地址返给main中的head,所以正确。

BubbleSort(head)也可以使用,只不过要变成引用,即
由Node *BubbleSort(Node *head)变成Node *BubbleSort(Node *&head)


[解决办法]
只输出了4。说明什么?


说明了只是将4的地址给了main()中的head.

热点排行