版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
不足之处请大牛指出
本代码实现了链式表的插入删除的基本功能
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iostream>
using namespace std;
typedef struct node{
int data;
struct node *next;
}Node,*LNode;
//创建一个带头节点的空单链表
LNode CreateListHead(void){
LNode L = (LNode)malloc(sizeof(Node));
if(!L)
exit(-1);
L->next = NULL;
return L;
}
//输出单链表
void DisLinkList(LNode L)
{
LNode p = L->next;
while(p){
printf("%d ",p->data);
p = p->next;
}
}
//求单链表长度
int ListLength(LNode L){
LNode p = L->next;
int k = 0;
while(p){
p = p->next;
k++;
}
return k;
}
//获取元素
int GetElem(LNode L,int pos, int *e){
LNode p = L->next;
int i = 1;
while(p && i<pos){
p=p->next;
++i;
}
if(!p || i>pos){
return 0;
}
*e = p->data;
return 1;
}
//插入元素
int ListInsert(LNode L,int pos, int e){
LNode p = L;
LNode pNew;
int i = 1;
while(p&& i<pos){
p = p->next;
++i;
}
if(!p || i<pos)
return 0;
pNew = (LNode)malloc(sizeof(Node));
pNew->data = e;
pNew->next = p->next;
p->next =pNew;
return 1;
}
//删除元素
int ListDelete(LNode L,int pos ,int *e){
LNode p = L;
LNode q;
int i=1;
while(p->next && i<pos)
{
p = p->next;
++i;
}
if(!(p->next) || i>pos)
return 0;
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return 1;
}
int main(void){
LNode L;
int e,f,g;
int a,b,c;
L = CreateListHead();
cout<<"链式表的初始长度"<<endl;
int n;
cin>>n;
cout<<"输入链式表的初始值"<<endl;
for(int i=1;i<=n;i++)
{
cin>>a;
ListInsert(L,i,a);
}
printf("输出单链表\n");
cout<<"插入操作"<<endl;
cout<<"插入的位置和大小"<<endl;
cin>>b>>c;
ListInsert(L,b,c);
DisLinkList(L);
printf("\n获取第三个元素\n");
GetElem(L,3,&e);
printf("%d\n",e);
printf("删除第四个元素\n");
ListDelete(L,4,&f);
printf("%d\n",f);
g=ListLength(L);
printf("单链表目前长度为%d\n",g);
return 0;
}