2022.2.6
单链表及其基本操作
(下一节 双链表及其基本操作)
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#define length 100
#define ElemType int
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode;
//初始化
void InitList(LNode *p){
p->next=NULL;
}
//尾插法创建链表 形参p为头节点
void GreateListR(LNode *p){
int a;
p->next=NULL;
LNode *r=p;
printf("input elem:\n");
while((scanf("%d",&a))==1){
LNode *s= (LNode *)malloc(sizeof(LNode));
s->data=a;
r->next=s;
r=s;
}
r->next=NULL;
}
//头插法创建链表 形参p为头节点
void GreateListL(LNode *p){
int a;
p->next=NULL;
LNode *r=p;
printf("input elem:\n");
while((scanf("%d",&a))==1){
LNode *s= (LNode *)malloc(sizeof(LNode));
s->data=a;
s->next=r->next;
r->next=s;
}
}
//按位序插入 在第i个位置插入元素e 带头节点
bool ListInsert(LNode *p,int i,ElemType e){
if(i<1)
return false;
int a=0;
LNode *r=p;
while(a!=i-1&&r!=NULL){
r=r->next;
a++;
}
if(r==NULL)
return false;
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=e;
s->next=r->next;
r->next=s;
return true;
}
//指定结点的后插(在p之后插入元素e)
bool InsertNextNode(LNode *p,ElemType e){
LNode *r=p;
if(r==NULL)
return false;
LNode *s=(LNode *)malloc(sizeof(LNode));
if(s==NULL)
return false;
s->data=e;
s->next=r->next;
r->next=s;
return true;
}
//指定结点的前插操作 (在p前面插入元素e)
bool InsertPriorNode(LNode *p,ElemType e){
LNode *r=p;
if(r==NULL)
return false;
LNode *s=(LNode *)malloc(sizeof(LNode));
if(s==NULL)
return false;
s->next=r->next;
r->next=s;
s->data=r->data;
r->data=e;
return true;
}
//按位序删除(删除i位置的元素并用e带回)
bool ListDelete(LNode *p,int i,int *e){
if(i<1)
return false;
int a=0;
LNode *r=p;
while(a!=i-1&&r!=NULL){
r=r->next;
a++;
}
if(r==NULL)
return false;
LNode *s=r->next;
*e=s->data;
r->next=s->next;
free(s);
return true;
}
//删除一个结点
bool DeleteNode(LNode *p){//p为要删除的结点 不是头结点 还有如果要删除的结点刚好是最后一个结点,就只能从头检索到倒数第二节结点去删 后面用双链表吧
LNode *s=p->next;
p->data=s->data;
p->next=s->next;
free(s);
return true;
}
//按值查找元素 找到元素e所在的位置并返回此结点
LNode *FindElem(LNode p,ElemType e){
LNode *r=p.next;
while(r!=NULL&&r->data!=e){
r=r->next;
}
return r; //找到了就返回结点 找不到就返回NULL;
}
//求表长
int Length(LNode p){
LNode *r=p.next;
int a=0;
while(r!=NULL){
a++;
r=r->next;
}
return a;
}
int main(){
LNode p;
InitList(&p);
GreateListR(&p);
ListInsert(&p,7,7);
LNode*q= FindElem(p,7);
InsertNextNode(q,8);
InsertPriorNode(q,1);
int a=Length(p);
printf("-----------%d\n",a);
return 0;
}