实验1链表的插入和删除
【实验目的】
1、 了解单链表、循环链表和双链表的基本知识;
2、 掌握算法思想和数据结构的描述;
3、 掌握链表的插入、删除的相关语句及基本方法。
【实验步骤与要求】
1、 实验前的准备
(1) 了解C语言的基本概念;
(2) 了解C语言的基本段落。
2、 上机操作
(1) 了解链表的基本知识;
(2) 掌握算法思想和数据结构的描述;
(3) 掌握链表的插入、删除的相关语句及基本方法。
【实验内容】
设有两个无头结点的单链表,头指针分别为ha,hb,链中有数据域data,链域next,两链表的数据都按递增序存放,现要求将hb表归到ha表中,且归并后ha仍递增序,归并中ha表中已有的数据若hb中也有,则hb中的数据不归并到ha中,hb的链表在算法中不允许破坏。
【方法说明】
先定义结构体:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
源代码1.1:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
void head_insert(LinkList *root,int x)
{
LNode *p=(LNode*)malloc(sizeof(LNode));
p->data=x;
p->next=*root;
*root=p;
}
void _union(LinkList *root1,LinkList *root2)
{
LNode *p=*root1,*q=*root2;
LinkList *last=root1;
while(p)
{
while(q&&q->data<=p->data)
{
if(q->data<p->data)
{
head_insert(last,q->data);
last=&((*last)->next);
}
q=q->next;
}
last=&(p->next);
p=p->next;
}
while(q)
{
head_insert(last,q->data);
q=q->next;
}
}
void show(LinkList p)
{
while(p)
{
printf("%d\n",p->data);
p=p->next;
}
}
int main()
{
LinkList ha=NULL,hb=NULL;
head_insert(&ha,10);
head_insert(&ha,5);
head_insert(&ha,4);
head_insert(&ha,1);
head_insert(&hb,8);
head_insert(&hb,5);
head_insert(&hb,3);
head_insert(&hb,2);
printf("----A----\n");
show(ha);
printf("----B----\n");
show(hb);
_union(&ha,&hb);
printf("----A----\n");
show(ha);
printf("----B----\n");
show(hb);
return