<pre name="code" class="cpp">/**
*Author:DTY
*E-Mail:clickyeah@yeah.net
*Date:2015.12.03
**/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
using namespace std;
typedef struct DNode{
int data;
struct DNode *pre;
struct DNode *next;
} DNode,*DList;
DList createDList() {
DList l=NULL;
int data=0;
int n=0;
DNode* cur=NULL;
while(scanf("%d",&data),data!=-1) {
DNode* tmpDNode = (DNode*)malloc(sizeof(DNode));
tmpDNode->data = data;
tmpDNode->next = NULL;
if(n==0) {
l=tmpDNode;
l->pre=NULL;
cur=l;
n++;
}
else {
tmpDNode->pre=cur;
cur->next=tmpDNode;
cur=tmpDNode;
}
}
return l;
}
void printDList(const DList& l) {
DNode* cur=l;
if(!cur) return;
printf("%d",cur->data);
cur=cur->next;
while(cur) {
printf(" %d",cur->data);
cur=cur->next;
}
printf("\n");
return;
}
void insertSort(DList& l) {
if(l==NULL || l->next==NULL) return;
DNode* cur = l->next;
while(cur) {
DNode* next=cur->next;
DNode* tmpDNode=cur->pre;
while(tmpDNode && tmpDNode->data > cur->data) {
tmpDNode=tmpDNode->pre;
}
if(tmpDNode==NULL) {
cur->pre->next=cur->next;
if(cur->next!=NULL) cur->next->pre=cur->pre;
l->pre = cur;
cur->next=l;
cur->pre=NULL;
l=cur;
}
else if(tmpDNode->next != cur) {
cur->pre->next=cur->next;
if(cur->next!=NULL) cur->next->pre=cur->pre;
else {
cur->pre=tmpDNode;
cur->next=tmpDNode->next;
tmpDNode->next->pre=cur;
tmpDNode->next=cur;
}
}
cur=next;
}
return;
}
void bubbleSort(DList& l) {
if(l==NULL || l->next==NULL) return;
DNode* tail = l;
while(tail->next) {
tail=tail->next;
}
int unsorted=1;
while(unsorted && tail!=l) {
unsorted=0;
DNode* front=l;
while(front!=tail) {
if(front->data > front->next->data) {
int t=front->data;
front->data=front->next->data;
front->next->data=t;
unsorted=1;
}
front = front->next;
}
tail = tail->pre;
}
}
int main(int argc, char* agv[]) {
while(DList l = createDList()) {
insertSort(l);
//bubbleSort(l);
printDList(l);
}
return 0;
}
hadoop@dream:~$ cat input
1 -1
1 2 3 4 5 -1
5 4 3 2 1 -1
3 4 5 1 2 -1
1 1 1 1 1 -1
-1
hadoop@dream:~$ g++ DList.cpp
hadoop@dream:~$ ./a.out <input
1
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 1 1 1 1
双向链表插入排序和冒泡排序
最新推荐文章于 2022-01-02 21:05:15 发布