#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node *Next;
}NODE,*PNODE;
PNODE createlist(){
int len;
int i;
int val;
PNODE pHead=(PNODE)malloc(sizeof(Node));
if(pHead==NULL)
{
printf("内存分配失败,程序结束!");
exit(-1);
}
PNODE pTail=pHead;
pTail->Next=NULL;
printf("请输入该链表的长度len=");
scanf("%d",&len);
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->Next=pNew;
pNew->Next=NULL;
pTail=pNew;
}
return pHead;
}
void traverselist(PNODE pHead)
{
PNODE p=pHead->Next;
while(p!=NULL){
printf("%d ",p->data);
p=p->Next;
}
}
bool empty(PNODE pHead)
{
if(NULL==pHead->Next)
return true;
else
return false;
}
int lenth(PNODE pHead){
int len=0;
PNODE p=pHead->Next;
while(p!=NULL)
{
++len;
p=p->Next;
}
return len;
}
void sort(PNODE pHead){
int i,j,t;
PNODE p,q;
int len=lenth(pHead);
for(i=0,p=pHead->Next;i<len-1;i++,p=p->Next)
{
for(j=i+1,q=p->Next;j<len;j++,q=q->Next){
if(p->data>q->data){
t=p->data;
p->data=q->data;
q->data=t;
}
}
}
return ;
}
bool insert(PNODE pHead,int pos,int val)
{
int i=0;
PNODE p=pHead;
while(p!=NULL&&i<pos-1)
{
p=p->Next;
++i;
}
if(i>pos-1||p==NULL)
{
return false;
}
PNODE pNew=(PNODE)malloc(sizeof(NODE));
if(pNew==NULL){
printf("内存分配失败,程序结束!");
exit(-1);
}
pNew->data=val;
PNODE q=p->Next;
p->Next=pNew;
pNew->Next=q;
return true;
}
bool deletelist(PNODE pHead,int pos,int *val)
{
int i=0;
PNODE p=pHead;
while(p->Next!=NULL&&i<pos-1)
{
p=p->Next;
++i;
}
if(i>pos-1||p==NULL)
{
return false;
}
PNODE q=p->Next;
*val=q->data;
p->Next=p->Next->Next;
free(q);
q=NULL;
return true;
}
int main(void)
{
int val;
PNODE pHead=NULL;
pHead=createlist();
traverselist(pHead);
int len =lenth(pHead);
printf("该链表的长度为%d\n",len);
printf("升序排序:");
sort(pHead);
traverselist(pHead);
printf("请输出插入后的序列:");
insert(pHead,2,3);
traverselist(pHead);
printf("请输出删除后的序列:");
deletelist(pHead,5,&val);
traverselist(pHead);
printf("删除的数为%d",val);
if(empty(pHead))
printf("链表为空!");
else
printf("not empty");
}
链表
最新推荐文章于 2024-07-15 22:08:02 发布