C语言 算法 数据结构 单链表

如何使用单链表L存储一批整数(值均不为0),将L中的所有负数放在正数之前。考虑头插法和尾插法重新建表。

生成20个结点的链表,将负数放在链表前面,正数放在负数后面,供参考:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node {
    int    x;
    struct node* next;
};
void print(struct node* head)
{
    struct node* p = head;
    while (p) {
        printf(p == head ? "%d" : " %d", p->x);
        p = p->next;
    }
    printf("\n");
}
int main()
{
    int i;
    struct node* head = NULL, * pt = NULL, * tail = NULL;
    srand((unsigned int)time(NULL));

    for (i = 0; i < 20; i++) {
        pt = (struct node*)malloc(sizeof(struct node));
        pt->next = NULL;
        pt->x = rand() % 20 - 10;
        if (head == NULL) {
            head = pt;
            tail = pt;
        }
        else {
            if (pt->x >= 0) { //正数  尾插
                tail->next = pt;
                tail = pt;
            }
            else {//负数   头插
                pt->next = head;
                head = pt;
            }
        }
    }
    print(head);
    return 0;
}

正数采用尾插法,负数采用头插法。分别定义头插法和尾插法的函数就行了。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^