c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}
// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int getListLength(Node* node)
{
int length = 0;
Node *tail = node;
while (node != NULL)
{
node = node->next;
length++;
}
return length;
}
LinkedList reverseList(Node* head)
{
Node* pre = NULL;
Node* cur = head;
while (cur != NULL)
{
Node* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
//冒泡排序
void bubbleSort(Node* head1)
{
Node* i = NULL;
Node* j = NULL;
for (i = head1; i != NULL; i = i->next)
{
for (j = i->next; j != NULL; j = j->next)
{
if (i->data > j->data)
{
int temp = i->data;
i->data = j->data;
j->data = temp;
}
}
}
}
int main() {
LinkedList head1 = NULL;
append(&head1, 1);
append(&head1, 3);
append(&head1, 2);
append(&head1, 6);
bubbleSort(head1);
printf("list : \n");
printList(head1);
system("pause");
return 0;
}
参考:https://blog.csdn.net/m0_72983118/article/details/128068313