AcWing 3477. 简单排序
原题链接
简单
作者:
雪落无声
,
2024-10-25 19:57:03
,
所有人可见
,
阅读 2
C++ 代码
#include<bits/stdc++.h>
using namespace std;
#define MAXSIZE 100
#define OVERFLOw -2
#define OK 1
#define ERROR 0
int a[1010];
typedef int Status;
typedef int eleType;
typedef struct LNode {
eleType data;
struct LNode *next;
} LNode, *LinkList;
//初始化一个空链表
Status LinkedListInit(LinkList &L){
L = new LNode;
if(!L) exit(OVERFLOw);
L->next = nullptr;
return OK;
}
//头 插 法
void LinkedListAddHead(LinkList &L,eleType value){
LNode * newNode = new LNode;
newNode->data = value;
newNode ->next = L->next;
L->next = newNode ;
}
//尾 插 法
void LinkedListAddTail(LinkList &L, eleType value) {
LNode* p = L;
LNode* newNode = new LNode;
newNode->data = value;
while (p->next!= nullptr) {
p = p->next;
}
newNode->next = p->next;
p->next = newNode;
}
//打印链表
void LinkedListPrint(LinkList &L){
LNode* p = L->next;
while(p){
cout<<p->data<<" ";
p = p->next;
}
}
void LinkListInsertSort(LinkList &L){
LNode * head = L;//头指针
LNode * order = head;//从头节点开始
LNode * disorder = head->next->next;//已经排序过的元素
LNode * front = head->next;//disorder的前指针
while(disorder != NULL){
while(order->next!=disorder){//每次都是order的后一个与disorder比较 所以条件是这个
if(order->next->data > disorder->data){
LNode * back = disorder->next;//存disorder的后指针 防止disorder前移时后链失踪
//开始前移至指定位置
disorder->next = order->next;
order->next = disorder;
front->next = back;//disorder前移那它一开始的前后指针接一块
disorder = front;//更新为disorder为它的前指针
//前移结束
break;
}
order = order->next;
}
front = disorder;//更新下disorder的前指针front
disorder = disorder->next;//更新disorder
order = head;//order再从头来
}
}
int main(){
int n;
cin>>n;
for(int i = 0;i<n;i++){
cin>>a[i];
}
LinkList L;
LinkedListInit(L);
for(int i = 0;i<n;i++){
LinkedListAddTail(L,a[i]);
}
LinkListInsertSort(L);
LNode * pre = L;
while(pre->next){
LNode * cur = pre->next;
if(pre->data==cur->data){
pre->next = cur->next;
delete cur;
}else pre = pre->next;
}
LinkedListPrint(L);
return 0;
}