标签:bsp next 插入 sizeof can 语言 bool free node
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE
{
int data ;
struct NODE * pNext ;
} * PNODE , NODE ;
PNODE create_list(void) ;
void traverse_list(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 * val);
int main()
{
PNODE pHead = NULL ;
pHead =create_list();
traverse_list(pHead);
printf("链表的长度是:%d\n",length_list(pHead) );
// sort_list(pHead);
// traverse_list(pHead);
int add ;
add=12 ;
if(insert_list(pHead,5,add) )//在第Pos个结点前面插入一个新的结点
{
printf("您增加的结点成功,值为%d\n",add) ;
traverse_list(pHead);
}
else printf("结点为空!\n") ;
int val ;
if(delete_list(pHead,5,&val) )
{
printf("您删除的结点成功,值为%d\n",val);
traverse_list(pHead);
}
else printf("删除的结点为空!\n") ;
}
PNODE create_list(void)
{
int val;
int len;
int i ;
printf("请输入您需要的结点个数:");
scanf("%d",&len);
PNODE phead = (PNODE)malloc(sizeof(NODE)) ;
if(phead ==NULL)
{
printf("动态分配内存失败!");
exit(-1);
}
PNODE pTail =phead ;
pTail->pNext = NULL ;
for(i=0;i<len;i++)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE)) ;
if(pNew ==NULL)
{
printf("动态分配内存失败!");
exit(-1);
}
printf("请输入第%d个结点的值:",i+1);
scanf("%d",&val);
pNew->data = val ;
pTail->pNext=pNew ;
pNew->pNext=NULL ;
pTail = pNew ;
}
return phead ;
}
void traverse_list(PNODE phead)
{
PNODE p = phead->pNext ;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->pNext ;
}
printf("\n");
}
int length_list(PNODE phead)
{
int len = 0 ;
PNODE p = phead->pNext ;
while(p!=NULL)
{
len++ ;
p=p->pNext ;
}
return len ;
}
void sort_list(PNODE phead)
{
int i,j,temp,len;
len = length_list(phead);
PNODE p = NULL ;
for(i=0;i<len-1;i++)
{
for(j=0,p=phead->pNext;j<len-i-1;j++,p=p->pNext)
{
if(p->data>p->pNext->data)
{
temp = p->data;
p->data=p->pNext->data;
p->pNext->data = temp ;
}
}
}
}
bool insert_list(PNODE phead,int Pos,int val) //是在第Pos个结点前面插入一个新的结点
{
int i=0;
PNODE p=phead;
while(p!=NULL && i<Pos-1)
{
p=p->pNext;
i++ ;
}
if(p==NULL && i>Pos-1)
return false ;
PNODE pNew=(PNODE)malloc(sizeof(NODE));
if(pNew ==NULL)
{
printf("动态分配失败!");
exit(-1);
}
pNew->data = val ;
PNODE q = p->pNext ;
p->pNext = pNew ;
pNew->pNext =q ;
return true ;
}
bool delete_list(PNODE phead,int Pos,int *val)
{
int i=0;
PNODE p =phead ;
while(p->pNext!=NULL && i<Pos-1)
{
p=p->pNext ;
i++;
}
if(p->pNext == NULL && i>Pos-1)
return false ;
PNODE q = p->pNext ;
*val = q->data ;
p->pNext =p->pNext->pNext ;
free(q);
q=NULL ;
}
标签:bsp next 插入 sizeof can 语言 bool free node
原文地址:https://www.cnblogs.com/cocobear9/p/12235304.html