算法-创建链表

掌握数据结构和算法,尤其是链表,面试编程题经常考

下面是用尾插法创建链表

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<malloc.h>
#include <string.h>

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

Node *LinkListCreat(int n)//链表创建函数
{
    Node *p;
    Node *head,*rear;
    int i = 0; 
    Node *Tal;
    
    head = (Node *)malloc(sizeof(Node));
    rear = head;
    rear->next = NULL;

    for (i = 0; i < n; i++)
    {
        p = (Node *)malloc(sizeof(Node));
         
        printf("请输入第%d个数:", i + 1);
        scanf("%d", &p->data);
        p->next = rear->next;
        rear->next = p;
        rear = p;
    
    }
    return head;

}
int LinkListOut(Node *p)//链表输出函数
{
    printf("输出链表:
");
    p = p->next;//头结点指向第一个结点
    int i=1;
    while (p->data != NULL)
    {
        printf("输出第%d个值为:%d
",i,p->data);
        i++;
        p = p->next;
    }

}
int  main()
{
    int a = 5;
    int i;
    Node *q;
    q=LinkListCreat(a);
    LinkListOut(q);
    free(q);


}

输出结果

头插法函数如下

Node *LinkListCreat(int n)//链表创建函数
{
    Node *p;
    Node *head,*rear;
    int i = 0; 
    Node *Tal;
    
    head = (Node *)malloc(sizeof(Node));
    head->next = NULL;

    for (i = 0; i < n; i++)
    {
        p = (Node *)malloc(sizeof(Node));
         
        printf("请输入第%d个数:", i + 1);
        scanf("%d", &p->data);
        p->next = head->next;
        head->next = p;
    
    }

输出结果如图

原文地址:https://www.cnblogs.com/cyyz-le/p/10994397.html