正负链表分离的另一种核心代码写法(C语言,带头节点)

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int Data;
    struct Node *Next;
};
void insert_tail(struct Node *L,int num){/*尾插法*/
    struct Node *p,*q;
    p=L;
    while(p->Next!=NULL){
        p=p->Next;
    }
    q=(struct Node *)malloc(sizeof(struct Node));
    q->Data=num;
    q->Next=p->Next;
    p->Next=q;
}
void show(struct Node *L){
    struct Node *p;
    p=L;
    while(p->Next!=NULL){
        p=p->Next;
        printf("%d\t",p->Data);
    }
    printf("\n");
}
struct Node *Split(struct Node *head1){/*链表分离的核心代码*/
    struct Node *p1,*p2,*q1,*head2;
    head2=(struct Node *)malloc(sizeof(struct Node));
    head2->Next=NULL;
    p1=head1;
    p2=head2;
    q1=head1->Next;
    while(q1){
        if(q1->Data>=0){
            p1->Next=q1;
            p1=q1;
            q1=q1->Next;
        }else{
            p2->Next=q1;
            p2=q1;
            q1=q1->Next;
        }
    }
    p1->Next=NULL;
    p2->Next=NULL;
    return head2;
}
int main(){
    struct Node *L,*Neg;
    L=(struct Node *)malloc(sizeof(struct Node));
    L->Next=NULL;
    int i;
    for(i=1;i<=6;i++){
        insert_tail(L,-i);
        insert_tail(L,i);
    }
    printf("原链表:");
    show(L);/*打印原有链表*/
    Neg=Split(L);
    printf("分离后非负链表:\n");
    show(L);/*打印分离后的非负链表*/
    printf("分离后负链表:\n");
    show(Neg);/*打印分离后的负链表*/
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值