链表实现冒泡排序
#include <iostream> #include <cstdio> #include <cstdio> #include <algorithm> #include <vector> #include <cstring> #include <string> #include <map> #include <stack> #include <list> #define NSY "Not sure yet.\n" #define IDG "In different gangs.\n" #define ITSG "In the same gang.\n" using namespace std; typedef struct node{ int data; struct node * next; } Node; void creat(Node **head) { int n,x; printf("请输入一个数表示有几个节点\n"); scanf("%d",&n); while(n--) { Node *cur=new node; scanf("%d",&x); cur->data=x; cur->next=*head; *head=cur; } } void print(Node *head) { Node *cur=head; while(cur) { printf("%d ",cur->data); cur=cur->next; } printf("\n"); } void Lsort(Node *head)//整体思想用的冒泡排序思想 { int x=0,t; Node *tail,*p,*next;//tail代表链表每一次排序后的未排序链表的最后一个节点 if(head==NULL) return; for(p=head;p->next!=NULL;p=p->next); tail=p; while(tail!=head) { for(p = head;p!=tail;p=p->next) { if(p->data > p->next->data)//比较p节点和p->next节点的data大小 { t=p->data;p->data=p->next->data;p->next->data=t; } next=p; } tail = next; } } int main() { //freopen("data.in","r",stdin); Node *head=NULL ; creat(&head); print(head); Lsort(head); print(head); return 0; }