随机生成100个整数存入链表,整数范围在[-100, 100]之间,输出该链表。将该链表分为两个,一个存放所有负整数,另一个存放所有非负整数,输出这两个链表。(C语言)

本文介绍了一种C语言实现的链表操作,通过Split函数将输入链表中的非负数和负数分别存放在两个独立链表中。使用了结构体和指针技巧,展示了如何根据数据值的正负进行有效分割,并演示了如何展示两个新的链表结果。
摘要由CSDN通过智能技术生成
#include<stdio.h>
#include<stdlib.h>
struct Node{
    int Data;
    struct Node *Next;
};
struct Node *create(){
    struct Node *head;
    head=(struct Node *)malloc(sizeof(struct Node));
    head->Next=NULL;
    return head;
}
void tail_insert(struct Node *head,int num){
    struct Node *p,*q;
    p=head;
    while(p->Next!=NULL){
        p=p->Next;
    }
    q=(struct Node *)malloc(sizeof(struct Node));
    q->Data=num;
    q->Next=p->Next;
    p->Next=q;
}
struct Node *Split(struct Node *head1){/*非负数保存在原链表,负数保存在新建链表中返回头节点*/
    struct Node *p1,*p2,*q1,*head2;
    head2=create();
    p1=head1;
    p2=head2;
    q1=p1->Next;
    while(q1){
        if(q1->Data<0){
            p2->Next=q1;
            p2=q1;
            q1=q1->Next;
            p2->Next=NULL;
        }else{
            p1->Next=q1;
            p1=q1;
            q1=q1->Next;
            p1->Next=NULL;
        }
    }
    return head2;
}
void show(struct Node *head){
    struct Node *p;
    p=head->Next;
    int count=0;
    while(p!=NULL){
        printf("%d\t",p->Data);
        count++;
        if(count%10==0){
            printf("\n");
        }
        p=p->Next;
    }
    printf("\n");
}

int main(){
    struct Node *head1,*head2;
    head1=create();
    srand(time(NULL));
    for(int i=0;i<100;i++){
        tail_insert(head1,rand()%201-100);
    }
    printf("原链表:\n");
    show(head1);
    head2=Split(head1);
    printf("分离后的负链表:\n");
    show(head2);
    printf("分离后的非负链表:\n");
    show(head1);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值