线性表
- 通常在单链表的开始节点之前附设一个类型相同的结点,成为头结点。加上头结点之后,无论单链表是否为空,头指针始终指向头结点,因此空表和非空表的处理也就统一了。
- 单链表中指针和结点之间的关系如下图所示:
- 单链表由头指针唯一确定,整个单链表的操作必须从头指针开始进行。通常设置一个工作指针p,当它
指向某结点时执行相应的处理,然后将指针修改为指向其后继结点,直到p为NULL为止。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
}Node;
Node * InitList()//初始化
{
Node*first=(Node*)malloc(sizeof(Node));
first->next=NULL;
return first;
}
int Empty(Node*first)//判空操作
{
if(first->next==NULL)return 1;
else return 0;
}
void PrintList(Node*first)//遍历操作
{
Node*p=first->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int Length(Node*first)//求长度
{
Node*p=first->next;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
int Locate(Node*first,DataType x)//按值查找
{
Node*p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x)return count;
p=p->next;
count++;
}
return 0;
}
int Get(Node*first,int i,DataType *ptr)//按位查找
{
Node *p=first->next;
int count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL){
printf("位置错误,查找失败\n");
return 0;
}
else{
*xptr=p->data;
return 1;
}
}
int Insert(Node*first,int i,DataType x)//插入操作
{
Node*s=NULL,*p=first;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL){
printf("位置错误,查找失败\n");
return 0;
}
else{
s=(Node*)malloc(sizeof(Node));
s->data=x;
s->next=p->next;
p->next=s;
return 1;
}
}
Node *CreatList(DataType a[],int n)//建立单链表(尾插法)
{
Node*s=NULL,*r=NULL;
Node*first=(Node*)malloc(sizeof(Node));
r=first;
for(int i=0;i<n;i++){
s=(Node*)malloc(sizeof(Node));
s->data=a[i];
r->next=s;r=s;
}
r->next=NULL;
return first;
}
int Delete(Node*first,int i,DataType *ptr)//删除操作
{
Node*p=first,*q=NULL;
int count =0;
DataType x;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL){
return 0;
}
else{
q=p->next;
*ptr=q->data;
p->next=q->next;
free(q);
return 1;
}
}
void DestroyList(Node*first)//销毁单链表
{
Node*p=first;
while(first!=NULL)
{
first=first->next;
free(p);
p=first;
}
}
int main()
{
int r[5]={1,2,3,4,5},i,x,y,num,m,n;
Node*first=NULL;
printf("请输入列表数字的数量:\n");
scanf("%d",&num);
printf("请输入%d个数字作为列表:\n",num);
for(i=0;i<num;i++)
{
scanf("%d",&r[i]);
}
first=CreatList(r,num);
printf("当前线性表的数据为:\n");
PrintList(first);
printf("\n");
printf("请输入要插入的位置和数字\n");
scanf("%d %d",&m,&n);
Insert (first,m,n);
printf("执行插入操作后数据为:\n");
PrintList(first);
printf("\n");
printf("当前线性表的长度为:%d\n",Length(first));
printf("请输入查找的元素值:\n");
scanf("%d",&x);
i=Locate(first,x);
if(i!=0)printf("元素%d的元素位置为:%d\n",x,i);
else printf("单链表中没有元素%d\n",x);
printf("请输入要删除第几个元素:\n");
scanf("%d",&i);
y=Delete(first,i,&x);
if(y==1){
printf("删除第%d个元素是%d,删除后数据为:\n",i,x);
PrintList(first);
}
else printf("删除操作失败\n");
printf("\n");
DestroyList(first);
return 0;
}
以上代码均通过Dev-C++,可编译、可运行。
以上代码可用于对单链表的各种基本操作。
代码执行情况如下图所示: