实现的操作:
1、判断单链表是否为空
2、尾插法建立单链表
3、头插法建立单链表
4、在第i个位置插入元素e
5、后插操作,在p节点之后插入元素e
6、前插操作,在p节点前插入元素e
7、按位序删除,删除第i个元素
8、按位查找
9、按值查找
10、求表的长度
代码
#include <stdio.h>
#include<malloc.h>
//带头节点单链表实现的基本操作
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//初始化
bool InitList(LinkList &L){
L=(LNode*)malloc(sizeof(LNode));
if(L==NULL){
printf("内存不足,分配失败!");
return false;
}
L->next=NULL;
return true;
}
//判断单链表是否为空
bool Empty(LinkList L){
if(L->next==NULL){
return true;
}
else return false;
}
//尾插法建立单链表
LinkList List_TailInsert(LinkList &L){
int x;//插入数据为整型
LNode *s,*r=L;
scanf("%d",&x);
while(x!=9999){//输入9999结束循环
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
//头插法建立单链表
LinkList List_HeadInsert(LinkList &L){
int x;
LNode *s;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
//在第i个位置插入元素e
bool ListInsert(LinkList &L,int i,int e){
if(i<1)
return false;
LNode *p=L;
int j=0;
while(p!=NULL&&j<i-1){
p=p->next;
j++;
}
if(p==NULL){
return false;
}
LNode *s=(LNode*)malloc(sizeof(LNode));
if(s==NULL){
printf("内存不足,分配失败!");
return false;
}
s->next=p->next;
p->next=s;
s->data=e;
return true;
}
//后插操作,在p节点之后插入元素e
bool InsertNextNode(LNode *p,int e){
if(p==NULL)
return false;
LNode *s=(LNode*)malloc(sizeof(LNode));
if(s==NULL){
printf("内存不足,分配失败!");
return false;
}
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
//前插操作,在p节点前插入元素e
bool InsertPriorNode(LNode *p,int e){
if(p==NULL){
return false;
}
LNode *s=(LNode*)malloc(sizeof(LNode));
if(s==NULL){
printf("内存不足,分配失败!");
return false;
}
s->data=p->data;
s->next=p->next;
p->next=s;
p->data=e;
return true;
}
//按位序删除,删除第i个元素
bool ListDelete(LinkList &L,int i,int &e){
if(i<1)
return false;
LNode *p=L;
int j=0;
while(p!=NULL&&j<i-1){
p=p->next;
j++;
}
if(p==NULL){
return false;
}
LNode *q=p->next;
e=q->data;
p->next=q->next;
free(q);
return true;
}
//按位查找
LNode* GetElem(LinkList &L,int i){
if(i<1)
return NULL;
LNode *p=L;
int j=0;
while(p!=NULL&&j<i-1){
p=p->next;
j++;
}
return p;
}
//按值查找
LNode *LocateElem(LinkList &L,int e){
LNode*p=L->next;
while(p!=NULL){
if(p->data==e)
return p;
else p=p->next;
}
}
//求表的长度
int Length(LinkList L){
int len=0;
LNode *p=L;
while(p->next!=NULL){
p=p->next;
len++;
}
return len;
}
//打印单链表
void Print(LinkList L){
LNode *p=L->next;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
int main()
{
LinkList L;
InitList(L);//初始化
L=List_TailInsert(L);
Print(L);
LinkList L2;
InitList(L2);//初始化
List_HeadInsert(L2);
Print(L2);
ListInsert(L2,3,999);//在第三个位置插入999
Print(L2);
int x;
ListDelete(L2,2,x);//删除第二个元素
Print(L2);
printf("%d\n",x);
LNode *t=GetElem(L2,1);//找到第一个节点
InsertNextNode(t,0);//在t节点之后插入0
Print(L2);
int length;
length=Length(L2);//计算表长
printf("%d\n",length);
int a;
scanf("%d",&a);
return 0;
}
测试结果: