初学数据结构-C语言-链表的创建及相关操作
# include<stdio.h># include<malloc.h>
# include<stdlib.h>
typedef struct LinkList
{
struct LinkList * pNext;
int data;
} LList, * pLL;
pLL Create_LList()
{
int SIZE;
int VAL;//临时存放用户输入的节点值
pLL pHead = (pLL)malloc(sizeof(LList));
if(pHead==NULL)//注意与(pHead->pNext==NULL)的区别
{
printf("创建失败,程序终止!\n");
exit(-1);
}
pLL pTail = pHead;
pTail->pNext = NULL;
printf("请输入链表节点个数:");
scanf("%d",&SIZE);
for(int i=0;i<SIZE;i++)
{
printf("\n请输入第%d个节点的值:",i+1);
scanf("%d",&VAL);
pLL pNew = (pLL)malloc(sizeof(LList));
if(pNew==NULL)
{
printf("创建失败,程序终止!\n");
exit(-1);
}
pNew->data = VAL;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
bool Is_Empty(pLL pHead)
{
if(pHead->pNext == NULL)
return true;
else
return false;
}
int Size_LList(pLL pHead)
{
pLL p = pHead->pNext;
int size=0;
while(p!=NULL)
{
size++;
p=p->pNext;
}
return size;
}
bool Insert_LList(pLL pHead, int val, int pos)
{
int i=0;
pLL p = pHead;
while(p != NULL && i<pos-1)
{
p=p->pNext;
i++;
}
if(p==NULL || i>pos-1)
return false;
pLL pNew=(pLL)malloc(sizeof(LList));
if(pNew==NULL)
{
printf("创建失败,程序终止!");
exit(-1);
}
pNew->data=val;
pLL q = p->pNext;
p->pNext=pNew;
pNew->pNext=q;
pNew=q;
return true;
}
bool Delete_LList(pLL pHead, int pos, int * pval)
{
int i=0;
pLL p = pHead;
while(p->pNext != NULL && i<pos-1)
{
p=p->pNext;
i++;
}
if(p->pNext==NULL || i>pos-1)
return false;
pLL q=p->pNext;
* pval=q->data;
p->pNext=p->pNext->pNext;
free(q);
q=NULL;
return true;
}
void Sort_LList(pLL pHead)
{
int i,j,t;
int size=Size_LList(pHead);
pLL p,q;
for(i=0, p=pHead->pNext;i<size-1;i++, p=p->pNext)
for(j=i+1, q=p->pNext;j<size;j++, q=q->pNext)
{
if(p->data>q->data)
{
t=p->data;
p->data=q->data;
q->data=t;
}
}
return;
}
bool Find_LList(pLL pHead, int val, int *pos)
{
pLL p=pHead->pNext;
int size=0;
for(p;p!=NULL;)
{
if(p->data==val)
{
*pos=size+1;
return true;
}
size++;
p=p->pNext;
}
if(p==NULL)
{
return 0;
}
}
void Traverse_LList(pLL pHead)
{
pLL p=pHead->pNext;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->pNext;
}
printf("\n");
}
int main()
{
pLL Head=NULL;
int size;
int pos,val;
Head=Create_LList();
if(Is_Empty(Head))
{
printf("\n链表为空,程序终止!\n");
exit(-1);
}
printf("\n创建的链表为:");
Traverse_LList(Head);
size = Size_LList(Head);
Sort_LList(Head);
printf("\n链表顺序排列为:");
Traverse_LList(Head);
printf("\n请输入要插入节点的值和位置:");
scanf("%d %d", &val, &pos);
if(Insert_LList(Head,val,pos))
{
printf("\n在第%d个位置插入%d后链表为:", pos, val);
Traverse_LList(Head);
}
else
printf("\n插入失败!\n");
printf("\n请输入要删除节点的位置:");
scanf("%d", &pos);
if(Delete_LList(Head, pos, &val))
{
printf("\n删除值为%d的节点后链表为:", val);
Traverse_LList(Head);
}
else
printf("\n删除失败!\n");
printf("\n请输入要查找节点的值:");
scanf("%d", &val);
if(Find_LList(Head, val, &pos))
printf("\n%d所在节点在第%d个位置\n", val, pos);
else
printf("\n没有找到值为%d的节点!\n", val);
return 0;
}