#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node * creat1(int n)//逆序建立链表
{
struct node *head,*p;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=head->next;
head->next=p;
}
return (head);
}
struct node * creat2(int n)//顺序建立链表
{
struct node *head,*p,*tail;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
return (head);
}
struct node *search(struct node *head,int key)//查找节点
{
struct node *p;
p=head->next;
while(p!=NULL)
{
if(p->data==key)
return (p);
else
p=p->next;
}
return NULL;
}
void insert(struct node *q,struct node *p,int key)//单链表节点的插入
{
q=(struct node *)malloc(sizeof(struct node));
if(!q)
{
printf("不能分配内存空间!n");
exit(0);
}
q->data=key;
q->next=NULL;
q->next=p->next;
p->next=q;
}
void del(struct node *head,int key)//删除节点
{
struct node *p,*q;
int flag=0;
p=head;
while(p->next!=NULL)
{
if(p->next->data==key)
{
flag=1;
break;
}
else
p=p->next;
if(flag==1)
{
q=p->next;
p->next=q->next;
free(q);
}
}
}
void reverse(struct node *head)//单链表的逆置
{
struct node *p,*q;
p=head->next;
head->next=NULL;
q=p->next;
while(p!=NULL)
{
p->next=head->next;
head->next=p;
p=q;
if(q!=NULL)
q=q->next;
}
}
struct node *merge(struct node *head1,struct node *head2)//单链表的归并
{
struct node *p1,*p2,*tail;
p1=head1->next;
p2=head2->next;
tail=head1;
free(head2);
while(p1&&p2)
{
if(p1->data<p2->data)
{
tail->next=p1;
tail=p1;
p1=p1->next;
}
else
{
tail->next=p2;
tail=p2;
p2=p2->next;
}
if(p1)
tail->next=p1;
else
tail->next=p2;
}
return (head1);
}
struct node *split(struct node *head1)//单链表的拆分
{
struct node *head2,*p,*q;
head2=(struct node*)malloc(sizeof(struct node));
head2->next=NULL;
p=head1->next;
head1->next=NULL;
q=p->next;
while(p!=NULL)
{
if(p->data>=0)
{
p->next=head1->next;
head1->next=p;
}
else
{
p->next=head2->next;
head2->next=p;
}
p=q;
if(q!=NULL)
q=q->next;
}
return (head2);
}
int main()
{
int m,n,k,d,j=0;
struct node *q,*h,*a,*y,*z;
scanf("%d",&n);
h=creat2(n);
//a=creat2(n);
/*
scanf("%d %d",&k,&m);
y=search(h,k);//链表的查找节点
insert(h,y,m);//在找到的节点后插入一个值
*/
/*
scanf("%d",&d);
del(h,d);//删除节点
*/
//reverse(h);//单链表的逆置
/*
z=merge(h,a);//单链表的归并
q=z->next;
y=split(h);
q=y->next;
*/
q=h->next;
while(q!=NULL)
{
j++;
if(j==n+1)
printf("%d\n",q->data);
else
printf("%d ",q->data);
q=q->next;
}
return 0;
}
链表的逆置,归并,拆分以及其他函数集合
最新推荐文章于 2022-04-19 22:31:54 发布