#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,*PNODE;
PNODE create_list(void);
void traverse_list(PNODE pHead);
bool is_empty(PNODE pHead);
int length_list(PNODE pHead);
void sort_list(PNODE pHead);
bool insert_list(PNODE pHead,int pos,int val);
bool delete_list(PNODE pHead,int pos,int * pVal);
PNODE create_list(void){
int len;
int val;
int i;
printf("请输入节点个数:");
scanf("%d",&len);
PNODE pHead = (PNODE)malloc(sizeof(NODE));
pHead->pNext = NULL;
PNODE pTail = pHead;
if(NULL==pHead){
printf("内存分配失败");
exit(-1);
}
for(i = 0;i<len;i++){
printf("请输入第%d个节点的值",i+1);
scanf("%d",&val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL==pHead){
printf("内存分配失败");
exit(-1);
}
pNew->data=val;
pTail->pNext=pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void traverse_list(PNODE pHead){
PNODE p = pHead->pNext;
while(NULL!=p){
printf("%d",p->data);
p=p->pNext;
}
return;
}
bool is_empty(PNODE pHead){
if(NULL == pHead->pNext){
return true;
}else{
return false;
}
}
int length_list(PNODE pHead){
PNODE p = pHead->pNext;
int cnt=0;
while(NULL!=p){
cnt = cnt+1;
p=p->pNext;
}
return cnt;
}
void sort_list(PNODE pHead){
int i,j,t;
PNODE p,q;
int len=length_list(pHead);
for(i=0,p=pHead->pNext;i<len;i++,p=p->pNext){
for(j=i+1,q=p->pNext;j<len;j++,q=q->pNext){
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
bool insert_list(PNODE pHead,int pos,int val){
int i = 0;
PNODE p = pHead;
while(NULL != p && i<pos-1){
p=p->pNext;
i++;
}
if(i>pos-1 || NULL==p){
return false;
}
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL==pNew){
printf("分配内存失败");
exit(-1);
}
pNew->data = val;
pNew->pNext = p->pNext;
p->pNext = pNew;
return true;
}
bool delete_list(PNODE pHead,int pos,int * pVal){
int i = 0;
PNODE p = pHead;
while(NULL != p->pNext && i<pos-1){
p=p->pNext;
i++;
}
if(i>pos-1 || NULL==p->pNext){
return false;
}
PNODE pOld = p->pNext;
*pVal = pOld->data;
p->pNext = p->pNext->pNext;
free(pOld);
pOld = NULL;
return true;
}
c语言链表的创建、插入、删除、排序
最新推荐文章于 2023-12-03 13:10:15 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)