1. 程式人生 > >新技能:連結串列1.5 get√

新技能:連結串列1.5 get√

# 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
*/