#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createList()
{
struct Node* headNode = (struct Node *)malloc(sizeof(struct Node));
headNode->next = NULL;
return headNode;
}
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode_head(struct Node* headNode, int data)
{
struct Node* newNode = createNode(data);
newNode->next = headNode->next;
headNode->next = newNode;
}
void BubbleSort(struct Node* headNode)
{
struct Node* firstNode = headNode->next;
struct Node* secondNode = headNode;
while(firstNode != NULL)
{
while(firstNode->next != NULL)
{
if(firstNode->data > firstNode->next->data)
{
int temp = firstNode->data;
firstNode->data = firstNode->next->data;
firstNode->next->data = temp;
}
firstNode = firstNode->next;
}
firstNode = secondNode->next;
secondNode = firstNode;
}
}
void printList(struct Node* headNode)
{
struct Node* t = headNode->next;
while(t)
{
printf("%d ", t->data);
t = t->next;
}
printf("\n");
}
int main()
{
struct Node* list = createList();
insertNode_head(list, 5);
insertNode_head(list, 2);
insertNode_head(list, 7);
insertNode_head(list, 3);
insertNode_head(list, 1);
printList(list);
BubbleSort(list);
printList(list);
return 0;
}
C语言单链表实现冒泡排序
最新推荐文章于 2023-03-10 12:55:18 发布