#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int id;
Node* next;
};
//初始化头节点
Node* init_m_head()
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->id = 0;
temp->next = NULL;
return temp;
}
//初始化子节点
Node* init_Node(int num)
{
Node* temp= (Node*)malloc(sizeof(Node));
temp->id = num;
temp->next = NULL;
return temp;
}
//节点链接
void nodelink(Node* n1, Node* n2)
{
n2->next = n1->next;
n1->next = n2;
}
//节点交换
void swap(Node* n1, Node* n2)
{
Node* temp = n1;
n1 = n2;
n2 = temp;
}
//void maopao(Node* list)
// {
// Node* temp = list->next;
// Node* pre = list;
// while (temp != NULL)
// {
// if (temp->id > temp->next->id)
// {
// pre->next = temp->next; //头节点挂到temp的节点后面
// temp->next = temp->next->next;
// temp->next->next = temp;
//
// }
// pre = temp; //
// temp = temp->next;
//
// }
// }
void maopao( Node * head)
{
Node * p, *q, *tail;
tail = NULL;
while ((head->next->next) != tail)
{
p = head;
q = head->next;
while (q->next != tail)
{
if ((q->id) > (q->next->id))
{
p->next = q->next;
q->next = q->next->next;
p->next->next = q;
q = p->next;
}
q = q->next;
p = p->next;
}
tail = q;
}
}
void node_printf(Node*list)
{
Node* temp = list->next;
if (temp == NULL)
{
printf("空表!\n");
return;
}
printf("链表打印为:\n");
while (temp)
{
printf("%d ", temp->id);
temp = temp->next;
}
}
int main()
{
Node* temp=init_m_head();//初始化头节点
Node* n1 = init_Node(1);
Node* n2 = init_Node(5);
Node* n3 = init_Node(2);
Node* n4 = init_Node(3);
nodelink(temp, n1);
nodelink(temp, n2);
nodelink(temp, n3);
nodelink(temp, n4);
maopao(temp);
node_printf(temp);
return 0;
}
来源:https://www.cnblogs.com/shenji/p/12578974.html