常見思路:
1,從前往後掃描,見到0元素先記數,再將後續一非0元素,前移並繼續掃描,全部掃完後再把後續部分清0``
2,從前往後掃描,見到0元素則與尾部非0元素互換
前期準備
#include<stdio.h>
#include<malloc.h>
typedef struct Lnode {
int date;
struct Lnode *next;
}Londe,*Linklist;//create a single list
//尾插法建立連結串列
Linklist CreateList(int n)
{
Linklist Head;//頭指標
Londe *p, *r;//建立連結串列的指標
Head = NULL, r = NULL;
if (n < 0)
{
return 0;
}
for (int i = 0; i < n+1; i++)
{
if (Head == NULL)
{
p = (Linklist)malloc(sizeof(Linklist));
p->date = NULL;//建立頭節點
r = p;
Head = p;
}
else {
p = (Linklist)malloc(sizeof(Linklist));
scanf("%d", p->date);
r->next = p;
r = p;
}
}
if (r != NULL)
r->next = NULL;
return Head;
}
void list_sort(Linklist L)
{
int count = 0;
Londe *p;
L = L->next;//移動到首元節點
p = L;
while (L->next != NULL)
{
if (L->date != 0) {
p->date = L->date;
p = p->next;
}
else count++;
L = L->next;
}
for (; count > 0; count--)
{
p->date = 0;
p = p->next;
}
}
void print(Linklist L)
{
L = L->next;
while (L != NULL)
{
printf("%d ", L->date);
L = L->next;
}
}
int main()
{
Londe *L = CreateList(5);
print(L);
list_sort(L);
printf("\n");
print(L);
}
歡迎各位大佬的指正與優化