单链表的建立

一、顺序建立链表(尾插法)

1、首先建立一个只需头结点的空链表,此时头指针、尾指针均指向头结点

 head=(struct node*)malloc(sizeof(struct node));
 head->next=NULL;

2、在头结点后插入第一个节点

p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail=head;
tail->next=p;
tail=p;

单链表的建立_第1张图片

3、之后插入节点的方法同上,用循环即可

单链表的建立_第2张图片

完成后的链表如下图:

完整代码如下:

struct node * creat(int n)
{
    struct node *head, *tail, *p;
    int i;
    head = (struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    tail = head;
    for(i=1; i<=n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    return (head);
}

二、逆序建立链表(头插法)

1、首先建立一个只包含头结点的空链表


 head=(struct node*)malloc(sizeof(struct node));
 head->next=NULL;
​

2、在头结点之后插入第一个节点

p = (struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next = head->next;
head->next = p;

单链表的建立_第3张图片

3、之后同上

单链表的建立_第4张图片

完成后的链表:

完整的代码:

struct node * create (int n)
{
    struct node *head, *p;
    int i;
    head = ​(struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    for(i=1; i<=n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next = head->next;
        head->next = p;
    }
    return (head);
}

你可能感兴趣的:(c语言)