资源描述
实验一 线性表
实验目的
1、 掌握线性表的逻辑结构和物理实现;
2、 掌握线性表的顺序存储结构和链式存储结构,熟悉对线性表的基本操作;
3、 在学有余力的情况下,掌握循环链表的实现及其基本操作;
4、 根据实验要求设计并完成程序,把理论的基本操作知识转化到实际的实践应用中。
课题一的具体实验内容
1、构造元素类型为整型的线性表,将以下元素插入分别插入线性表:
<34 56 20 9 15 5>
2、查找表中是否存在元素20,实现元素20与元素9的交换;
3、 按照课题要求编写函数,实现线性表元素<34 56 9 20 15 5>的倒置,即倒置后的表应为< 5 15 20 9 56 34 >。
主程序代码
#include<stdio.h>
#include<stdlib.h>
#define NULL 0
struct node
{
int num;
struct node *next;
};
void main()
{
int i,flag=1;
struct node *L,*s,*p,*h,*q,*k,*p1,*temp;
L=(node*)malloc(sizeof(struct node));
p=L; printf("请输入\n");
for(i=0;i<6;i++)
{
s=(node*)malloc(sizeof(struct node));
scanf("%d",&s->num);
p->next=s;
p=s;
}
p->next=NULL; //以上是链表的建立和输入
//以下为a元素交换
p=L;
while(p->next->num!=20&&p->next->next!=NULL)
p=p->next;
if(p->next->next==NULL)
{
printf("sorry,can not find!\n");
flag=0;
printf("原表括倒置后输出\n");
}
else if (p->next->num==20)
{
flag=1;
printf("find it!\n");
}
if(flag==1)
{
h=p->next;
p->next=p->next->next;
h->next=p->next->next;
p->next->next=h;
//以下为链表括的输出
printf("交换后输出\n");
p=L->next;
while(p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}
printf("倒置后输出\n");
}
//以下为链表括的倒置
p1=L->next;
temp=p1->next;
p1->next=NULL;
p=temp;
while(temp!=NULL)
{ p=p->next;//移动原链表的指针?
temp->next=p1;
L->next=temp;
p1=temp;//需插入节点的指向移动
temp=p;
}
//以下为链表输出
p=L->next;
while(p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}
printf("\n");
}
展开阅读全文