请教个单向链表的排序问题。。。。小妹
To All:
大家好。如题。
1.创建个单项链表。
2.用冒泡实现排序。
3.能够输出正确结果。
小妹的代码如下:
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;}