#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node
{
int data; //数据域
struct Node * pNext; //指针域
}NODE, *PNODE; //NODE等价于 struct Node PNODE等价于struct Node *
PNODE create_list(void);
void traverse_list(PNODE pHead);
bool is_empty(PNODE pHead);
int length_list(PNODE);
bool insert_list(PNODE,int,int);
bool delete_list(PNODE,int,int *);
void sort_list(PNODE);
int main()
{
PNODE pHead = NULL; //等价于struct Node * pHead = NULL;
int val;
pHead = create_list();
traverse_list(pHead);
if(delete_list(pHead,4,&val)){
printf("删除成功,您删除的元素是:%d\n",val);
}
else{
printf("删除失败!删除元素不存在!\n");
}
traverse_list(pHead);
//insert_list(pHead,4,99);
//traverse_list(pHead);
//if(is_empty(pHead)){
// printf("链表为空!\n");
//}else{
// printf("链表不为空!\n");
//}
//int len = length_list(pHead);
//printf("链表长度是%d\n",len);
//sort_list(pHead);
//traverse_list(pHead);
return 0;
}
//功能:创建一个非循环单链表,并将该链表的头结点的地址赋给pHead
PNODE create_list(void)
{
int len; //用来存放有效节点个数
int i = 0;
int val; //用来临时存放用户输入节点的值
//分配了一个不存放数据的头节点,pHead是指向头结点的头指针
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if(NULL==pHead){
printf("分配失败,程序终止!\n");
exit(-1);
}
//尾结点永远指向最后一个节点
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("请输入您要生成的链表节点数:len = ");
scanf("%d",&len);
for(;i<len;i++){
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val); //scanf后不要加\n,程序容易出错
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL == pNew){
printf("分配失败,程序终止!\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pNew;
}
printf("\n");
return pHead;
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while(NULL != p){
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
return;
}
bool is_empty(PNODE pHead)
{
if(pHead->pNext == NULL){
return true;
}
else{
return false;
}
}
int length_list(PNODE pHead)
{
PNODE p = pHead->pNext;
int len = 0;
while(p!=NULL){
++len;
p = p->pNext;
}
return len;
}
void sort_list(PNODE pHead)
{
int i,j,t;
int len = length_list(pHead);
PNODE p,q;
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)
{
if(p->data>q->data){
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
return;
}
//在pHead所指向链表的第pos个节点前面插入一个节点,该节点的值是val,并且pos的值从1开始
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("动态分配错误!\n");
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 q = p->pNext;
*pVal = q->data;
//删除p后面的节点
p->pNext = p->pNext->pNext;
free(q); //释放q所指向的节点内存
q = NULL; //消除指针变量q的联系,要不就是野指针了
return true;
}
数据结构:链表List
最新推荐文章于 2020-11-23 19:22:18 发布