#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status; //状态
typedef int ElemType; //元素类型
typedef struct Node{
ElemType data;
struct Node* next;
} Node;
typedef struct Node* LinkList; //定义指向链表元素指针
Status GetElem(LinkList head,int i,ElemType* data){ //得到链表元素,存到data里面
LinkList p=head;
p=p->next;
int j=1;
while(p&&j<i){
p=p->next;
j++;
}
if(!p||j>i){
return ERROR;
}
*data=p->data;
return TRUE;
}
Status InsertElem(LinkList* head,int i,ElemType data){ //插入链表元素
LinkList prev=*head;
LinkList current=*head;
current=current->next;
int j=1;
while(current&&j<i){
prev=current;
current=current->next;
j++;
}
if(!current || j>i)
return ERROR;
LinkList new_node=malloc(sizeof(Node));
new_node->data=data;
prev->next=new_node;
new_node->next=current;
return TRUE;
}
Status DeleteElem(LinkList* head,int i,ElemType* data){
LinkList prev=*head;
LinkList current=prev;
current=current->next;
int j=1;
while(j<i&¤t){
prev=current;
current=current->next;
j++;
}
if(!current || j>i)
return ERROR;
LinkList temp=current;
*data=current->data;
prev->next=current->next;
current->next=NULL;
free(temp);
}
Status CreateList(LinkList* L,int n){
LinkList p,r;
int i;
srand(time(0));
*L=(LinkList) malloc(sizeof(Node));
r=*L; //指向尾部节点
for(i=0;i<n;i++){
p=(Node*) malloc(sizeof(Node));
p->data=rand()%100+1;
r->next=p;
r=p;
}
r->next=NULL;
}
Status ClearList(LinkList* L){
LinkList current=(*L)->next;
LinkList temp;
while(current){
temp=current->next;
free(current);
current=temp;
}
(*L)->next=NULL;
return OK;
}
int main(void){
LinkList L;
if(CreateList(&L,100))
printf("success create LinkList\n");
int data;
int nums=3;
if(GetElem(L,nums,&data)){
printf("success get element,the %dth element is %d\n",nums,data);
}
data=100;
if(InsertElem(&L,nums,data)){
printf("success insert element,the %dth element is %d\n",nums,data);
}
if(DeleteElem(&L,nums,&data)){
printf("success delete element,the %dth element is %d\n",nums,data);
}
if(ClearList(&L)){
printf("success clear LinkList\n");
}
return 0;
}
Data structures lying heavy brush - to achieve single chain ADT
Guess you like
Origin blog.csdn.net/qq_41603639/article/details/104858388
Ranking