阅读背景:

将两个升序排列的单链表合并为一个降序排列的单链表且不增加新的结点

来源:互联网 
#include<stdio.h>
#include<stdlib.h>

typedef struct node{
	char data;
	struct node *next;
}LNode;

LNode *creat_linklist()
{
	LNode *p,*q,*head;
	int i,n;
	head=(LNode*)malloc(sizeof(LNode));
	head->next=NULL;
	p=head;
	q=p;
	printf("请输入单链表长度:\n");
	scanf("%d",&n);
	printf("请输入值:\n");
	for(i=1;i<=n;i++)
	{
		p=(LNode*)malloc(sizeof(LNode));
		scanf("%d",&p->data);
		p->next=NULL;
		q->next=p;
		q=p;
	}
	return head;
}

void merge(LNode *A,LNode *B,LNode **C)
{
	LNode *p,*q,*s;
	p=A->next;
	q=B->next;
	*C=A;
	(*C)->next=NULL;
	free(B);
	while(p!=NULL&&q!=NULL)
	{
		if(p->data<q->data)
		{
			s=p;
			p=p->next;
		}
		else
		{
			s=q;
			q=q->next;
		}
		s->next=(*C)->next;
		(*C)->next=s;
	}
	if(p==NULL)
		p=q;
	while(p!=NULL)
	{
		s=p;
		p=p->next;
		s->next=(*C)->next;
		(*C)->next=s;
	}
}

void print(LNode *p)
{
	p=p->next;
	while(p!=NULL)
	{
		printf("%5d",p->data);
		p=p->next;
	}
	printf("\n");
}

void main()
{
	LNode *A,*B,*C;
	printf("*** 创建单链表A ***\n");
	A=creat_linklist();
	printf("您创建的单链表A为:\n");
	print(A);
	printf("\n");
	printf("*** 创建单链表B ***\n");
	B=creat_linklist();
	printf("您创建的单链表B为:\n");
	print(B);
	printf("\n合并之后的单链表C为:\n");
	merge(A,B,&C);
	print(C);
}#include<stdio.h>
#include<stdlib.h>

typedef s



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: