代码片
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Ceshi{
int date;
struct Ceshi* pNext;
}Ce,*Pce;
Pce Create_list(){
int len;
int val;
int i;
Pce pHead=(Pce)calloc(sizeof(Ce),1);
Pce pTail=pHead;
if(pHead==NULL){
printf("内存分配失败,程序结束!");
exit(-1);
}
printf("请输入字符串的长度:");
scanf("%d",&len);
for(i=0;i<len;i++){
Pce pNext=(Pce)calloc(sizeof(Ce),1);
if(pNext==NULL){
printf("内存分配失败,程序结束!");
exit(-1);
}
printf("请输入第%d个字符:",i+1);
scanf("%d",&val);
pNext->date=val;
pTail->pNext=pNext;
pTail=pNext;
pNext->pNext=NULL;
}
return pHead;
}
void traverse(Pce pHead){
if(pHead==NULL){
printf("内部为空!");
}
Pce p=pHead->pNext;
while(p){
printf("%d\t",p->date);
p=p->pNext;
}
printf("\n");
}
bool isempty(Pce pHead){
if(pHead->pNext==NULL){
return true;
}
return false;
}
int lengh_list(Pce pHead){
Pce p=pHead->pNext;
int lenght=0;
while(p){
lenght++;
p=p->pNext;
}
return lenght;
}
void sort_list(Pce pHead){
Pce p,q;
int i,j,t;
int len=lengh_list(pHead);
for(i=0,p=pHead->pNext;i<len;p=p->pNext,i++){
for(j=i+1,q=p->pNext;j<len;q=q->pNext,j++){
if(p->date>q->date){
t=p->date;
p->date=q->date;
q->date=t;
}
}
}
}
void insert_list(Pce pHead,int pos,int val){
int i;
Pce p=pHead;
while(i<pos-1&&p!=NULL){
p=p->pNext;
i++;
}
Pce pNext=(Pce)calloc(sizeof(Pce),1);
if(pNext==NULL||i>pos-1){
printf("内存分配失败!程序终止!");
exit(-1);
}
Pce q;
q=p->pNext;
pNext->date=val;
p->pNext=pNext;
pNext->pNext=q;
return true;
}
bool delete_list(Pce pHead,int pos,int* val){
Pce p=pHead;
int i=0;
while(i<pos-1&&p->pNext!=NULL){
p=p->pNext;
i++;
}
if(i>pos-1||p->pNext==NULL){
return false;
}
Pce q=p->pNext;
*val=q->date;
p->pNext=p->pNext->pNext;
free(q);
q=NULL;
return true;
}
int main(){
Pce pHead=NULL;
pHead=Create_list();
traverse(pHead);
int delete;
if(delete_list(pHead,3,&delete)){
printf("删除成功!,删除的元素是:%d\n",delete);
traverse(pHead);
}else{
printf("删除失败!");
}
return 0;
}