開始複習鏈表,今天寫了兩個函數,一個創建節點,一個遍歷節點

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

typedef struct node
{
    int data;
    struct node *pNext;    
}Node;

Node *create_list()
{
    int i;
    int num;
    int val;
    
    Node *phead = (Node *)malloc(sizeof(char));
    if(phead == NULL)
    {
        printf("分配內存失敗,程序終止!\n");
        exit(-1);
    }
    
    Node *ptail = phead;
    phead->pNext = NULL;
    
    printf("請輸入你想創建的節點個數:\n");
    scanf("%d",&num);
    
    for(i = 0;i < num;i++)
    {
        printf("請輸入第%d個節點的值:\n",i + 1);
        scanf("%d",&val);
        
        Node *pnew = (Node *)malloc(sizeof(Node));
        if(pnew == NULL)
        {
            printf("分配內存失敗,程序終止\n");
            exit(-1);
        }
        
        pnew->data = val;
        
        ptail->pNext = pnew;
        pnew->pNext = NULL;
        ptail = pnew;
    }
    
    return phead;
}

void traverse_list(Node *phead)
{
    Node *ptr = phead;
    if(ptr->pNext == NULL)
    {
        printf("該鏈表爲空!\n");
        return ;
    }
    while (ptr->pNext != NULL)
    {
        printf("%d\t",ptr->pNext->data);
        ptr = ptr->pNext;
    }
    printf("\n");
}

int main()
{
    Node *phead = NULL;
    phead = create_list();
    
    traverse_list(phead);
    
    return 0;
}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章