#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int flag;
//建立链表
node *creat(struct node *head)
{
int x;
struct node *p;
head->next=NULL;
scanf("%d",&x);
while(x)
{
p=(node *)malloc(sizeof(node));
p->data=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return head;
}
//打印链表
void output(struct node *head)
{
struct node *p;
p=head->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n\n");
}
//查找结点
void find(struct node *head,int n)
{
struct node *p=head;
int j=0;
while(j<n&&p)
{
j++;
}
if(!p||j>n)
{
printf("查找结点失败!\n");
flag=1;
return ;
}
else
printf("查找结点成功!\n\n");
return ;
}
//查找输入的数字
void find1(struct node *head,int n)
{
struct node *p=head;
int flag=0;
while(p)
{
if(p->data==n)
{
flag=1;
break;
}
p=p->next;
}
if(!flag)
{
printf("查找结点失败!\n");
return ;
}
else
printf("查找结点成功!\n\n");
return ;
}
//插入结点
node *insert(struct node *head,int n,int m)
{
struct node *s,*p;
int j=0;
s=(node *)malloc(sizeof(node));
s->data=n;
if(m==1)
{
s->next=head;
head=s;
return head;
}
p=head;
while(j<m&&p)
{
p=p->next;
j++;
}
printf("插入成功!\n\n");
s->next=p->next;
p->next=s;
return head;
}
//删除结点
node *delete_node(struct node *head,int n)
{
struct node *p,*q;
int j=0;
if(n==1)
{
q=head;
head=head->next;
free(q);
return head;
}
p=head;
while(j<n&&p->next)
{
p=p->next;
j++;
}
q=p->next;
p->next=q->next;
free(q);
printf("删除结点成功!\n");
return head;
}
//合并链表
void creat1(struct node *head)
{
int x;
struct node *p,*s,*q,*s1,*s2,*head1,*head2;
head1=(node *)malloc(sizeof(node));
head2=(node *)malloc(sizeof(node));
s=head->next;
s1=head1;
s2=head2;
x=s->data;
while(s)
{
if(s->data>x)
{
p=(node *)malloc(sizeof(node));
p->data=s->data;
s1->next=p;
s1=p;
}
else
{
q=(node *)malloc(sizeof(node));
q->data=s->data;
s2->next=q;
s2=q;
}
s=s->next;
}
s1->next=NULL;
s2->next=NULL;
printf("合并后第一个链表为:\n");
output(head1);
printf("合并后第二个链表为:\n");
output(head2);
}
int main()
{
struct node *head,*s;
int i,n,m,x;
flag=0;
head=(node *)malloc(sizeof(node));
printf("输入链表:\n");
creat(head);
printf("打印链表:\n");
output(head);
printf("输入要插入的结点:\n");
scanf("%d",&i);
find(head,i);
if(!flag)
{
printf("输入要插入的值:\n");
scanf("%d",&n);
insert(head,n,i);
printf("打印链表:\n");
output(head);
}
printf("输入要删除的结点:\n");
scanf("%d",&m);
find(head,m);
if(!flag)
{
delete_node(head,m);
printf("打印链表:\n");
output(head);
}
printf("输入要查找的数字:\n");
scanf("%d",&x);
find1(head,x);
printf("合并链表:\n");
creat1(head);
return 0;
}