如何創建一個帶頭結點的有序的單鏈表?
鏈表在創建的時候就把它創建成有序的會顯得專業許多(霧),
而不是先創建無序鏈表再排序;
拿一道典型例題舉個栗子,相信你們都見過這道題;
Problem Description
輸入N個無序的整數,建立一個有序鏈表,鏈表中的結點按照數值非降序排列,輸出該有序鏈表。
Input
第一行輸入整數個數N;
第二行輸入N個無序的整數。
Output
依次輸出有序鏈表的結點值。
Sample Input
6
33 6 22 9 44 5
Sample Output
5 6 9 22 33 44
Hint
不得使用數組!
那麼思路是什麼呢?
我們可以再輸入新的結點時逐個進行查找與插入操作,這樣建立的就是有序的鏈表啦
#include<stdio.h>
struct node
{
int data;
struct node * next;
};
struct node * sort(struct node * p,int x)
{
struct node *ph,*pte,*paf;
ph=p;
pte = (struct node *)malloc(sizeof(struct node));
pte->data = x;pte->next = NULL;
while (p->next)
{
paf = p->next;
if (paf->data >= x)
{
pte->next = p->next;
p->next = pte;
return ph;
}
p = p->next;
}
pte->next = p->next;
p->next = pte;
return ph;
//while外表示的是創建第一個結點和最後一個結點時的情況
//大小排序爲p<pte<=paf
}
void list(struct node *p)
{
p = p->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
struct node *ph;
ph = (struct node *)malloc(sizeof(struct node));
ph->next = NULL;
int n, i, x;
scanf("%d", &n);
for (i = 0;i < n;i++)
{
scanf("%d", &x);
ph = sort(ph, x);
}
list(ph);
getchar();
getchar();
return 0;
}