#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node
{
int data; //数据域
struct Node * pNext; //指针域
}NODE, *PNODE; //NODE等价于struct Node PNODE等价于struct Node *
PNODE init(PNODE pHead);
bool is_empty(PNODE pHead);
int size(PNODE pHead);
PNODE add(PNODE pHead, PNODE pTail, int val);
PNODE add(PNODE pHead, int val);
void traveres(PNODE pHead); //遍历链表
bool insert_list(PNODE pHead, int pos, int val);
bool del(PNODE pHead, int pos);
int main(void)
{
PNODE pHead = NULL;
pHead = init(pHead);
PNODE pTail = pHead;
pTail->pNext = NULL;
pTail = add(pHead, pTail, 1); //注意,改变pTail地址的方式,通过返回值的形式或者通过改变地址值
pTail = add(pHead, pTail, 2);
pTail = add(pHead, pTail, 3);
insert_list(pHead, 2, 11);
del(pHead, 1);
traveres(pHead);
printf("size=%d ", size(pHead));
return 0;
}
PNODE add(PNODE pHead, PNODE pTail, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("分配失败, 程序终止!\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pNew;
return pTail;
}
PNODE init(PNODE pHead){
pHead = (PNODE)malloc(sizeof(NODE));
return pHead;
}
bool is_empty(PNODE pHead){
if(NULL == pHead->pNext){
return true;
}else{
return false;
}
}
int size(PNODE pHead){
PNODE p = pHead->pNext;
int i = 0;
while (NULL != p)
{
i++;
p = p->pNext;
}
return i;
}
void traveres(PNODE pHead)
{
PNODE p = pHead->pNext;
while (NULL != p)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
//pos从1开始,也就是当pos=2,在第二个位置之前插入元素
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(NULL==p || i > pos-1){ //NULL==p校验pos的长度大于链表的长度,i > pos-1校验pos为0或负数的情况
return false;
}
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("动态分配内存失败!\n");
exit(-1);
}
pNew->data = val;
PNODE temp = p->pNext;
p->pNext = pNew;
pNew->pNext = temp;
return true;
}
bool del(PNODE pHead, int pos)
{
int i=0;
PNODE p = pHead;
while(NULL != p && i<pos-1){
p = p->pNext;
}
if(NULL == p || i>pos-1){
return false;
}
PNODE temp = p->pNext;
p->pNext = p->pNext->pNext;
free(temp);
temp = NULL;
return true;
}