本文主要是介绍Qsort对链表指针排序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
数组元素为head头指针
头指针是结构体指针
- 排序方式:
- 链表元素少的排前面
- 元素个数相同的按字典序排序
Qsort 只能对连续的元素排序
#include <stdio.h>
#include <stdlib.h>typedef struct TagNode{int data;struct TagNode *next;
}Node;Node *CreateLink(int *arr, int n)
{Node *head = (Node *)malloc(sizeof(Node));head->data = *arr;Node *rear = head;Node *temp;for (int i = 1; i < n; ++i) {temp = (Node *)malloc(sizeof(Node));temp->data = *(arr + i);temp->next = NULL;rear->next = temp;rear = rear->next;}return head;
}int GetLinkLen(Node *head)
{int len = 0;Node *temp = head;while(temp){len++;temp = temp->next;}return len;
}int cmp(const void *head1, const void *head2)
{int len1 = GetLinkLen((Node *)head1);int len2 = GetLinkLen((Node *)head2);Node *temp1 = (Node *)head1;Node *temp2 = (Node *)head2;if (len1 == len2){while (temp1 && temp1->data == temp2->data){temp1 = temp1->next;temp2 = temp2->next;}return temp1 ? temp1->data - temp2->data : 0;}else {return len1 - len2;}
}void PrintLink(Node *head)
{printf("%#X: ", (unsigned int)head);while(head){printf("%d%s", head->data, head->next ? "-->" : "\n");head = head->next;}
}void FreeLink(Node *head)
{Node *temp;while(head){temp = head->next;free(head);head = NULL;head = temp;}
}#define ARR_LEN 3
Node *g_pNodeArr[ARR_LEN];void Initdata()
{int arr1[] = {2, 3, 4, 6};int arr2[] = {6, 2, 4, 5};int arr3[] = {5, 3, 1};g_pNodeArr[0] = CreateLink(arr1, 4);g_pNodeArr[1] = CreateLink(arr2, 4);g_pNodeArr[2] = CreateLink(arr3, 3);
}int main()
{Initdata();printf("---------------BEFORE QSORT-------------\n");for (int i = 0; i < ARR_LEN; ++i){PrintLink(g_pNodeArr[i]);}qsort(g_pNodeArr, sizeof(g_pNodeArr), sizeof(Node *), cmp);printf("---------------AFTER QSORT-------------\n");for (int i = 0; i < ARR_LEN; ++i){PrintLink(g_pNodeArr[i]);}for (int i = 0; i < ARR_LEN; ++i){FreeLink(g_pNodeArr[i]); }getchar();return 0;
}
- 排序函数有问题
这篇关于Qsort对链表指针排序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!