#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;
}
随机生成100个整数存入链表,整数范围在[-100, 100]之间,输出该链表。将该链表分为两个,一个存放所有负整数,另一个存放所有非负整数,输出这两个链表。(C语言)
最新推荐文章于 2022-11-17 10:55:02 发布
本文介绍了一种C语言实现的链表操作,通过Split函数将输入链表中的非负数和负数分别存放在两个独立链表中。使用了结构体和指针技巧,展示了如何根据数据值的正负进行有效分割,并演示了如何展示两个新的链表结果。
摘要由CSDN通过智能技术生成