数据结构——求单链表排序

求单链表排序

集合的运算如下:
原 集 合A: c a e h
原 集 合B: f h b g d a
有序集合A: a c e h
有序集合B: a b d f g h

代码中包含三个关于排序的自定义函数,均是冒泡排序
排序方法1:交换结点,多定义了一个指针
排序方法2:交换数据,结点不变
排序方法3:参考网上代码,优化交换结点排序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OK 1

typedef char elemtype;
typedef int  Status;

typedef struct LNode {
	elemtype data;
	struct LNode *next;
} LNode,*LinkList;

Status InitList(LinkList &L) {
	L=(LinkList)malloc(sizeof(LNode));
	if(!L)  exit(-1);
	L->next=NULL;
	return OK;
}

Status ListInsert_L(LinkList &L,int i,elemtype e) {
	LinkList p=L,q;
	int j=0;
	for(; p&&j<i-1; j++)
		p=p->next;
	if(p&&j>i-1)  return -1;
	q=(LinkList)malloc(sizeof(LNode));
	q->data=e;
	q->next=p->next;
	p->next=q;
}

Status ListPritnt_L(LinkList &L) {
	LinkList p=L;
	for(p=p->next; p; p=p->next) {
		printf("%c ",p->data);
	}
	printf("
");
}

Status ListLength(LinkList &L) {
	int i=0;
	LinkList p=L->next;
	while(p) {
		p=p->next;
		i++;
	}
	return i;
}

Status ListSort_L1(LinkList &L) { //交换结点的冒泡排序
	LinkList p,q,p_prior;
	int i,j,n;
	n=ListLength(L);
	for(i=1; i<n; i++) {
		p=L->next;
		q=p->next;
		p_prior=L;
		for(j=0; j<n-i; j++) {
			if((p->data)>(q->data)) {
				p_prior->next=q;
				p->next=q->next;
				q->next=p;
				//交换后的更新结点情况和没交换时不同
				p_prior=q;
				q=p->next;
			} else {
				p_prior=p;
				p=q;
				q=q->next;
			}
		}
	}
	p=q=p_prior=NULL;
}


Status ListSort_L2(LinkList &L) { //直接交换内部元素
	LinkList p,q;
	elemtype temp;
	int i,j,n;
	n=ListLength(L);
	for(i=1; i<n; i++)
		for(j=0,p=L->next,q=p->next; j<n-i; p=q,q=q->next,j++) {
			if((p->data)>(q->data)) {
				temp=p->data;
				p->data=q->data;
				q->data=temp;
			}
		}
	p=q=NULL;
}

void BubbleSort(struct LNode * head) { 
	//https://www.cnblogs.com/darkchii/p/7302412.html
	struct LNode * p, * q, * tail;

	tail = NULL;

	while((head->next->next) != tail) {
		p = head;
		q = head->next;
		while(q->next != tail) {
			if((q->data) > (q->next->data)) {
				p->next = q->next;
				q->next = q->next->next;
				p->next->next = q;
				q = p->next;
			}
			q = q->next;
			p = p->next;
		}
		tail = q;
	}
}

int main() {
	elemtype A[10]= {'c','a','e','h'};
	elemtype B[10]= {'f','h','b','g','d','a'};
	int i;
	LinkList head1,head2;
	InitList(head1);
	InitList(head2);

	for(i=0; A[i]; i++) {
		ListInsert_L(head1,i+1,A[i]);
	}
	printf("原 集 合A:");
	ListPritnt_L(head1);

	for(i=0; B[i]; i++) {
		ListInsert_L(head2,i+1,B[i]);
	}
	printf("原 集 合B:");
	ListPritnt_L(head2);

	//ListSort_L1(head1);
	BubbleSort(head1); 
	ListSort_L2(head2);
	printf("有序集合A:");
	ListPritnt_L(head1);
	printf("有序集合B:");
	ListPritnt_L(head2);
	
}
原文地址:https://www.cnblogs.com/vivid-victory/p/10090480.html