#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node * pNext;
} * pNode,Node;
pNode init();
bool append(pNode pHead,int data);
void show(pNode pHead);
int length(pNode pHead);
bool insert(pNode pHead,int data,int index);
bool del(pNode pHead,int index);
void main()
{
pNode pHead = init();
int len = length(pHead);
printf("%d\n",len);
append(pHead,3);
append(pHead,4);
append(pHead,10);
insert(pHead,555,1);
show(pHead);
del(pHead,1);
int len2 = length(pHead);
printf("%d\n",len2);;
show(pHead);
}
pNode init()// 初始化一个有头结点的空链表。
{
pNode pHead = (pNode)malloc(sizeof(Node));
if(NULL == pHead){
exit(-1);
}
else{
printf("初始化成功!\n");
pHead->pNext = NULL;
}
return pHead;
}
bool append(pNode pHead,int data)//在链表尾部追加一个元素。
{
pNode p = pHead;
while(p->pNext != NULL)
{
p = p->pNext;
}
pNode pNew = (pNode)malloc(sizeof(Node));
if(pNew != NULL)
{
pNew->data = data;
pNew->pNext = NULL;
p->pNext = pNew;
return true;
}
else
return false;
}
void show(pNode pHead)//打印链表
{
pNode p = pHead;
p = p->pNext;
while(p != NULL)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}
int length(pNode pHead)//返回链表长度
{
pNode p = pHead;
int len = 0;
p = p->pNext;
while(NULL != p)
{
p = p->pNext;
len++;
}
return len;
}
bool insert(pNode pHead,int data,int index)//在链表Index位置插入一个元素data,当插入的元素位置大于长度时,返回失败。
{
pNode pNew = (pNode)malloc(sizeof(Node));
pNode p = pHead;
int count = 0;
int len = length(pHead);
if(index > len || index < 1)
{
printf("插入序列号不正确\n");
return false;
}
else
{
while(NULL!=pNew && count!=index-1)
{
p = p->pNext;
count++;
}
pNew->data = data;
pNew->pNext = p->pNext;
p->pNext = pNew;
return true;
}
}
bool del(pNode pHead,int index)//删除index位置的元素,当index大于链表的长度时,删除失败。
{
pNode p = pHead;
int count = 0;
int len = length(pHead);
if(index > len||index< 1 )
{
printf("不存在该节点\n");
return false;
}
else{
while(count != index-1)
{
p = p->pNext;
count++;
}
pNode q = p->pNext;
p->pNext = p->pNext->pNext;
free(q);
return true;
}
}
</pre><pre name="code" class="cpp">少了反转和返回删除的元素。。。下次在实现吧。。。。