C语言对链表排序

hea.h

typedef struct Node_s {
	int data;
	struct Node_s* pNext;
} Node_t, *pNode_t;
void tailInsert(pNode_t *ppHead, pNode_t *ppTail, int data);
int myCompare(const void *p1, const void *p2);

main.c

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include "head.h"
#define N 6
int main() {
	pNode_t pHead = NULL;
	pNode_t pTail = NULL;
	int data;
	while (scanf("%d", &data) != EOF) {
		tailInsert(&pHead, &pTail, data);
	}
    //建立索引数组
	pNode_t index[N] = { NULL };
	pNode_t pCur = pHead;
	for (int i = 0; i < N; ++i) {
		index[i] = pCur;
		pCur = pCur->pNext;
	}
    //对索引数组排序
	qsort(index, N, sizeof(pNode_t), myCompare);
    //根据排序后的索引数组调整链表结构
	pHead = index[0];
	pTail = index[N - 1];
	for (int i = 0; i < N - 1; ++i) {
		index[i]->pNext = index[i + 1];
	}
	pTail->pNext = NULL;
}
void tailInsert(pNode_t *ppHead, pNode_t *ppTail, int data) {
	pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
	pNew->data = data;
	if (*ppHead == NULL) {
		*ppHead = pNew;
		*ppTail = pNew;
	}
	else {
		(*ppTail)->pNext = pNew;
		*ppTail = pNew;
	}
}
int myCompare(const void *p1, const void *p2) {
    //强制转化成以元素类型为基类型的指针,这里变成了二级指针
	pNode_t *pleft = (pNode_t *)p1;
	pNode_t *pright = (pNode_t *)p2;
	return (*pleft)->data - (*pright)->data;
}

你可能感兴趣的:(C++,c语言,链表,开发语言)