首页 > 代码库 > 单链表冒泡排序(交换节点)
单链表冒泡排序(交换节点)
代码如下:
#include<iostream>#include<cstdlib>using namespace std;int num;typedef struct list{ int data; struct list *next;}Lnode,*linklist;linklist Createlist(int n)//构建带头结点的链表{ linklist p, head,tail; head = (linklist)malloc(sizeof(Lnode)); tail = NULL; head->next = tail; for (int i = 0; i < n; i++) { p = (linklist)malloc(sizeof(Lnode)); cin >>p-> data; p->next = NULL; if (tail == NULL) head->next = p; else tail->next = p; tail=p; } return head;//返回头结点的地址}void sortlist(linklist head)//对链表进行bubble sort{ linklist pre, p,tail; tail = NULL; while (head->next != tail) { pre = head; p = head->next; while (p->next!=tail) { if (p->data > p->next->data) { pre->next = p->next; p->next = pre->next->next; pre->next->next = p; } else p = p->next; pre = pre->next; } tail = p; }}int main(){ cin >> num; linklist head,x; head = Createlist(num); sortlist(head); x = head->next; while (x != NULL) { cout << x->data; x = x->next; } cout << endl; return 0;}
单链表冒泡排序(交换节点)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。