#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node*next;
};
struct node *create(void)
{
printf("\nPlease create your Link:\n");
struct node *head,*p1,*p2;
head=NULL;
p1=p2=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->data);
while(p1->data!=0){
if(head==NULL)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->data);
}
p2->next=NULL;
return (head);
}
void print(struct node*head)
{
struct node *p=head;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
struct node* del(struct node *head)
{
int n;
printf("\nPlease enter the number:\n");
scanf("%d",&n);
struct node*p1,*p2;
p1=p2=(struct node*)malloc(sizeof(struct node));
p1=p2=head;
if(head==NULL){
printf("\nNULL list\n");
return head;
}
else{
while(p1->data==n&&p1==head){head=head->next;p1=p2=head;}
while(p1!=NULL){
if(p1->data!=n){p2=p1;p1=p1->next;}
else {p2->next=p1->next;free(p1);p1=p2->next;}
}
}
print(head);
return head;
}
struct node*sort(struct node*head)
{
if(head==NULL){
printf("\nNULL list\n");
return head;
}
struct node*p1,*p2;
p1=p2=(struct node*)malloc(sizeof(struct node));
p1=head;
int temp;
while(p1!=NULL){
p2=p1->next;
while(p2!=NULL){
if(p1->data>p2->data){
temp=p1->data;
p1->data=p2->data;
p2->data=temp;
}
p2=p2->next;
}
p1=p1->next;
}
print(head);
return head;
}
struct node*insert(struct node*head)
{
int n;
printf("\nThe number to insert:\n");
scanf("%d",&n);
struct node*p=(struct node*)malloc(sizeof(struct node));
p->data=n;
struct node*head1,*head2;
head1=head;
if(head==NULL){head=p;p->next=NULL;}
else{
while(head1->data<p->data&&head1->next!=NULL){
head2=head1;head1=head1->next;
}
if(head1->data>=p->data){
if(head1==head){p->next=head;head=p;}
else {p->next=head1;head2->next=p;}
}
else {head1->next=p;p->next=NULL;}
}
print(head);
return head;
}
struct node*mergenodes(struct node*L1,struct node*L2)
{
struct node* HEAD,*La;
if(L1->data<L2->data){HEAD=La=L1;L1=L1->next;}
else {HEAD=La=L2;L2=L2->next;}
while (L1!=NULL&&L2!=NULL){
if(L1->data>L2->data){
La->next=L2;
La=L2;
L2=L2->next;
}
else{
La->next=L1;
La=L1;
L1=L1->next;
}
}
if(L1!=NULL){
La->next=L1;
}
if(L2!=NULL){
La->next=L2;
}
print(HEAD);
return HEAD;
}
int main()
{
struct node *L1=create();
struct node *L2=create();
sort(L1);
sort(L2);
mergenodes(L1,L2);
//struct node *head=create();
//print(head);
//sort(head);
//insert(head);
//del (head);
//insert(head);
return 0;
}
动态链表创建删除插入排序合并(C语言初学者)
最新推荐文章于 2024-07-14 14:55:20 发布