Linked List Wanli Algorithm

# include <stdio.h>

# include <malloc.h>
# include <stdlib.h>

typedef struct Node
{
int data; //data field
struct Node *pNext;//pointer field

} NODE, *PNODE; //NODE is equivalent to struct Node PNODE is equivalent to struct Node *


//function declaration
PNODE create_list(void);
void traverse_list(PNODE pHead);

int main(void)
{
PNODE pHead =NULL;// equivalent to struct PNODE * pHead=NULL

pHead=create_list(); //create a non- Circulate the singly linked list and assign the address of the head node of the linked list to pHead;
traverse_list(pHead);

return 0;

}

PNODE create_list(void)
{
int len; //Used to store the number of valid nodes
int i;
int val ;

//A header node
PNODE that does not store valid data is allocated pHead =(PNODE)malloc(sizeof(NODE));
if (NULL == pHead)
{
printf("Allocation failed, terminate program\n");
exit (-1);
}
PNODE pTail =pHead;
pTail->pNext =NULL;

printf("Please enter the number of nodes you need to generate the linked list: len = ");
scanf("%d",len);

for(i=0; i<len; ++i)
{
printf("Please enter the value of the %dth node: ", i+1);
scanf("%d",&val);

PNODE pNew =(PNODE )malloc(sizeof(NODE));
if (NULL == pHead)
{
printf("Allocation failed, terminate program\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 ;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326032540&siteId=291194637