# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,*PNODE;
PNODE create();
int length(PNODE);
void insert(PNODE,int,int);
void delet(PNODE);
bool empty(PNODE);
void add(PNODE);
void prlist(PNODE);
int main ()
{
PNODE pHead;
pHead = create();
add(pHead);
prlist(pHead);
delet(pHead);
prlist(pHead);
printf("链表长度为:%d\n",length(pHead));
return 0;
}
PNODE create()
{
PNODE pHead,pTail,pNew;
int len,i=1;
pHead = (PNODE)malloc(sizeof(NODE));
if(pHead == NULL)
{
printf("动态分配内存失败\n");
exit(-1);
}
pTail = pHead;
printf("输入所要创建链表的长度:");
scanf ("%d",&len);
while (i <= len)
{
printf("输入第%d个元素的值:",i);
scanf("%d",&pTail->data);
pNew = (PNODE)malloc(sizeof(NODE));
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pNew;
i++;
}
return pHead;
}
bool empty(PNODE * pHead)
{
if(pHead==NULL)
return true;
else
return false;
}
int length(PNODE pHead)
{
PNODE p;
p = pHead;
int con=0;
while (p->pNext != NULL)
{
p = p->pNext;
con++;
}
return con;
}
void add(PNODE pHead)
{
PNODE p,pTail,pNew;
int i,len,j=1;
p = pHead;
for(i=1;i<length(pHead);i++)
{
p=p->pNext;
}
p->pNext = (PNODE)malloc(sizeof(NODE));
pTail = p->pNext;
printf("输入所要追加链表的长度:");
scanf ("%d",&len);
while (j <= len)
{
printf("输入追加的第%d个元素的值:",j);
scanf("%d",&pTail->data);
pNew = (PNODE)malloc(sizeof(NODE));
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pNew;
j++;
}
return;
}
void prlist(PNODE pHead)
{
PNODE p;
p = pHead;
printf("链表数值依次为:");
while(p->pNext != NULL)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
}
void delet(PNODE pHead)
{
int order;
PNODE p,q;
int i;
printf ("输入你所要删除元素次序:");
scanf("%d",&order);
p=pHead;
for(i=1;i<order-1;i++)
{
p = p->pNext;
}
q = p->pNext;
p->pNext = q->pNext;
printf("删除的元素数值为%d:",q->data);
free(q);
printf("\n");
}
/*
2014-6-2 19:16:42
by zhao
*/