单链表的一些基本操作

#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}*LinkList;
  1. //头插法建立单链表
LinkList CreateList1(LinkList &L){
LNode *s;//定义结点指针
int x;
L=(LinkList)malloc(sizeof(LNode));//建立头结点
L->next=NULL;//初始化为空链表
scanf("%d",&x);
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));//创建新结点
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;//返回的是一个指针类型的数据
}
//尾插法建立单链表
LinkList CreateList2(LinkList &L){
LNode *s,*rear;
int x;
L=(LNode*)malloc(sizeof(LNode));
rear=L;///////////////////////////////////////////////////////////////////////////////////////
printf("Please input the value:");
printf("\n");
scanf("%d",&x);
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
rear->next=s;
//s=rear;
rear=s;
scanf("%d",&x);
}
rear->next=NULL;///////////////////////////////////////////////////////////////////////
printf("yes");
printf("\n");
return L;
}
//初始化链表
void InitList(LinkList &L){
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
}
//查找单链表的第i个位置的指针
LNode *GetElem(LinkList L,int i){
int j=1;//////////////////////////////////////////////////////
LNode *p;
p=L->next;
if(i<1){
return NULL;
}
while(p&&j<i){
p=p->next;
j++;
}
return p;
}
//查找元素e在单链表中的位置
LNode *LocateList(LinkList L,ElemType e){/////////////////////////////////////////////////////////
LNode *p;
p=L->next;
while(p->data!=e&&p){
p=p->next;
}
if(p==NULL){
return NULL;
}
return p;
}
//在单链表的第i个位置插入元素e
bool InsertList1(LinkList &L,int i,ElemType e){//方法1
LNode *p,*s;
s=(LNode*)malloc(sizeof(LNode));
s->data=e;
if(i<1){
return false;
}
p=GetElem(L,i-1);
s->next=p->next;
p->next=s;
return true;
}
//在单链表的第i个位置插入元素e
bool InsertList2(LinkList &L,int i,ElemType e){//方法2
LNode *p,*s;
ElemType temp;
s=(LNode*)malloc(sizeof(LNode));
s->data=e;
if(i<1){
return false;
}
p=GetElem(L,i);
if(p==NULL){
printf("插入数据位置不合理");
}
s->next=p->next;
p->next=s;
temp=p->data;
p->data=s->data;//交换数据域
s->data=temp;
return true;
}
//删除单链表中第i个元素
bool DeleteList1(LinkList &L,int i){//方法1
LNode *p,*s;
if(i<1){
return false;
}
p=GetElem(L,i-1);
s=p->next;
p->next=s->next;
free(s);
return true;
}
//删除单链表中第i个元素
bool DeleteList2(LinkList &L,int i){//方法2
LNode *p,*s;
ElemType temp;
if(i<1){
return false;
}
p=GetElem(L,i-1);
s=p->next;
temp=s->data;
p->data=temp;//和后继结点交换数据域
p->next=s->next;//断开后继结点
free(s);
return true;
}


//删除单链表中值为e的元素
bool DeleteList3(LinkList L,ElemType e){
LNode *p;
p=L->next;
while(p&&p->data!=e){
p=p->next;
}
if(p==NULL){
return false;
}
free(p);
return true;
}
//输出单链表
void PrintList(LinkList L){
LNode *p;
p=L->next;
while(p){
printf("%d",p->data);
p=p->next;
//printf("yes");
}
}


void main(){
LNode *h;
InitList(h);
CreateList2(h);
PrintList(h);
InsertList1(h,3,3);
printf("\n");
PrintList(h);
printf("\n");
InsertList1(h,4,4);
PrintList(h);
printf("\n");
DeleteList1(h,2);
PrintList(h);
}






















猜你喜欢

转载自blog.csdn.net/duminjun00a/article/details/80776484