1. 程式人生 > >鏈表萬歷算法

鏈表萬歷算法

一個 n) 聲明 next turn void lis printf truct

# 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 create_list(void);
void traverse_list(PNODE pHead);

int main(void)
{
PNODE pHead =NULL;// 等價於struct PNODE * pHead=NULL

pHead=create_list(); //創建一個非循環單鏈表,並將該鏈表的頭結點地址賦給pHead;
traverse_list(pHead);

return 0;

}

PNODE create_list(void)
{
int len; //用來存放有效節點的個數
int i;
int val;

//分配了一個不存放有效數據的頭結點
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=0; i<len; ++i)
{
printf("請輸入第%d個節點的值:", i+1);
scanf("%d",&val);

PNODE pNew =(PNODE)malloc(sizeof(NODE));
if (NULL == pHead)
{
printf("分配失敗,終止程序\n");
exit (-1);
}
pNew->data =val;
pTail->pNext =pNew;
pNew->pNext =NULL;
pTail = pNew;

}
return pHead;
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;

while(NULL !=p)
{
printf("%d",p->data);
p =p->pNext;
}
printf("\n");
return ;
}

鏈表萬歷算法