單鏈表氣泡排序
阿新 • • 發佈:2019-01-29
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<unordered_map>
#include<fstream>
#include<sstream>
#include<queue>
#include<stack>
#include<map>
#include<unordered_map>
#include<utility>
#include <iomanip>
#include<forward_list>
using namespace std;
struct node{
node* next;
int val;
};
void inital(node *head){
node *cur = head;
int tem;
while (cin >> tem){
node *n = new node();
n->val = tem;
cur->next = n;
cur = n;
}
cur-> next = NULL;
}
void bubble_List(node *head){
int tem;
node* tail = NULL;
while (tail != head->next)
{
node* pre = head;
node* cur = pre->next;
while (cur != tail && cur->next != tail)
{
if (cur->val > cur->next-> val)
{
//交換當前節點和後一個節點
/* pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = cur;*/
tem = cur->val;
cur->val = cur->next->val;
cur->next->val = tem;
}
pre = pre->next;
cur = pre->next;
}
tail = cur;
}
}
void print(node *head){
node *cur = head->next;
while (cur != NULL){
cout << cur->val << " ";
cur = cur->next;
}
}
int main(){
node *head=new node();
inital(head);
bubble_List(head);
print(head);
return 0;
}