线性表的操作
顺序表的操作可视为一维数组的操作,不予赘述。
线性链表的基本操作:构造链表以及对其增删查改等,在此列出在指定位置插入节点和删除节点的代码(C语言实现)。
头文件以及类型定义
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef struct
{
ElemType *Data;
int Length;
}Linear_List;//动态定义线性表(顺序结构)
typedef struct ListNode
{
ElemType Data;
struct ListNode *next;
}Chain_List;//线性表(链式结构)
构造线性链表
Chain_List *CreateList_Chain(int Length)
{
Chain_List *p;
Chain_List *p_run;//滚动指针(尾插法时用)
Chain_List *p_head=(Chain_List *)malloc(sizeof(Chain_List));
printf("input the data:");
scanf("%d",&p_head->Data);//此处未建立头结点(头结点直接存放了第一个数据)
p_head->next=NULL;
p_run=p_head;
for(int i=0;i<Length-1;i++)
{
p=(Chain_List *)malloc(sizeof(Chain_List));
printf("input the data:");
scanf("%d",&p->Data);
p->next=NULL;
// p->next=p_head->next;
// p_head->next=p;//头插法建立链表
p_run->next=p;
p_run=p;//尾插法建立链表
}
return p_head;
}
在指定位置插入新节点
Chain_List *Insert(Chain_List *List,ElemType Data_Inserted,int Length,int Position)
//链表的插入操作,Data_Inserted给定插入数据,Length给定表长,Position给定插入位置
{
Chain_List *p=(Chain_List *)malloc(sizeof(Chain_List));
p->Data=Data_Inserted;
p->next=NULL;
//待插入指针(携带待插入数据)
Chain_List *p_run=List;
//滚动指针
int i_Record=1;
if(Position==Length+1)
//插入尾端
{
while(p_run->next)
p_run=p_run->next;
//滚动指针到达尾节点
p_run->next=p;
//尾端插入
p->next=NULL;
Length++;
return List;
}
if(Position==1)
//插入头端
{
p->next=List;
List=p;
Length++;
return List;
}
while(i_Record!=Position-1)
//插入除头尾指定位置
{
p_run=p_run->next;
i_Record++;
}
//滚动指针到达待插入位置前端
p->next=p_run->next;
p_run->next=p;
//插入操作
Length++;
return List;
}
在指定位置删除节点
Chain_List *Delete(Chain_List *List,int Length,int Position)
//链表的删除操作,Length给定表长,Position给定删除位置
{
Chain_List *p_run=List;
int i_Record=1;
if(Position==1)
//若指定删除头节点,将头指针后移,释放原头结点
{
List=List->next;
free(p_run);
return List;
}
while(i_Record!=Position-1)
//滚动指针找到删除位(指向删除位前一个元素)
{
p_run=p_run->next;
i_Record++;
}
Chain_List *p_Deleted=p_run->next;
//记录删除位
p_run->next=p_run->next->next;
//前一元素指向隔两个元素
p_Deleted->next=NULL;
//删除位后继置空
free(p_Deleted);
//释放删除位
return List;
}
打印线性链表
void PrintChain(Chain_List *List)
{
Chain_List *p=List;
for(;p;p=p->next)
printf("%d ",p->Data);
printf("\n");
}
测试主函数
int main()
{
Chain_List *MyList;
int Length;
printf("input the length:");
scanf("%d",&Length);
MyList=CreateList_Chain(Length);
PrintChain(MyList);
ElemType TestData;
int Position_Insert;
printf("input the data you want to insert:");
scanf("%d",&TestData);
printf("input the position you want to insert your new data:");
scanf("%d",&Position_Insert);
MyList=Insert(MyList,TestData,Length,Position_Insert);
PrintChain(MyList);
int Position_Delete;
printf("input the position you want to delete:");
scanf("%d",&Position_Delete);
MyList=Delete(MyList,Length,Position_Delete);
PrintChain(MyList);
return 0;
}