#include <stdio.h>
#include <cstdlib>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*Linklist;
bool InitList(Linklist &L){
L = (LNode *)malloc(sizeof (LNode));
if(L==NULL)
return false;
L->next = NULL;
return true;
}
LNode * GerElem(Linklist L,int i){
if(i<0) return NULL;
LNode *p = L;
int j=0;
while (p->next!=NULL&&j<i){
p=p->next;
j++;
}
return p;
}
LNode * LocationElem(Linklist L,int e){
LNode *p=L->next;
while (p->next!=NULL&&p->data!=e)
p=p->next;
return p;
}
int Length(Linklist L){
LNode *p=L;
int count=0;
while (p->next!=NULL){
count++;
p=p->next;
}
return count;
}
bool InsertNextNode(LNode *p,int e){
if(p==NULL) return false;
LNode *s = (LNode *)malloc(sizeof (LNode));
if(s==NULL) return false;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
bool InsertPriorNode(LNode *p,int e){
if(p==NULL) return false;
LNode *s = (LNode *)malloc(sizeof (LNode));
if(s==NULL) return false;
s->next=p->next;
p->next=s->next;
s->data=p->data;
p->data=e;
return true;
}
bool ListDelete(Linklist &L,int i,int &e){
if(i<1) return false;
LNode *p = GerElem(L,i-1);
if(p==NULL) return false;
LNode *q=p->next;
p->next=q->next;
e=q->data;
free(q);
return true;
}
bool DeleteNode(LNode *p){
if(p==NULL) return false;
LNode *q=p->next;
p->data=q->data;
p->next=q->next;
free(q);
return true;
}
bool ListInsert(Linklist &L,int i,int e){
if(i<1) return false;
LNode *p=GerElem(L,i-1);
return InsertNextNode(p,e);
}
int main() {
Linklist L;
int e=0;
InitList(L);
for(int i=0;i<10;i++){
ListInsert(L,1,i);
}
printf_s("倒序前的列表为\n");
for(int i=1;i<Length(L)+1;i++){
printf_s("%d",GerElem(L,i)->data);
ListDelete(L,i,e);
InsertNextNode(L,e);
}
printf_s("\n倒序后的列表为\n");
for(int i=1;i<Length(L)+1;i++){
printf_s("%d",GerElem(L,i)->data);
}
return 0;
}
2.3单链表的基本操作
于 2021-07-05 14:02:18 首次发布