#include <iostream>
using namespace std;
struct Node
{
int no;
Node *next;
};
Node *input();
void insertsort(Node *&);
void output(Node *);
int main()
{
Node *list = input();
insertsort(list);
output(list);
}
Node *input()
{
Node *head = NULL;
int x;
cin >> x;
while (x != -1)
{
Node *p = new Node;
p->no = x;
if (head == NULL)
{
head = p;
head->next = NULL;
}
else
{
p->next = head;
head = p;
}
cin >> x;
}
return head;
}
void output(Node *head)
{
for (Node *p = head; p != NULL; p = p->next)
cout << p->no << " ";
cout << endl;
}
void insertsort(Node *&head)
{
if (head == NULL)
return;
Node *B = head->next;
head->next = NULL;
while (B != NULL)
{
Node *current = B;
B = B->next;
Node *A = head, *preA = NULL;
while (A && current->no > A->no)
{
preA = A;
A = A->next;
}
//此时已经确定了current的位置,在A之前,preA之后
if (preA == NULL)
{
current->next = head;
head = current;
}
else
{
preA->next = current;
current->next = A;
}
}
}
插入排序之链表实现
最新推荐文章于 2023-12-19 14:50:57 发布