MENU

头插和尾插

April 7, 2020 • 笔记

/*
 * @Author: Mr.Sen
 * @LastEditTime: 2020-04-07 18:10:25
 * @Website1: 449293786.site
 * @Website2: sluowanx.cn
 */
#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
    int data;
    struct node *next;
}lNode,*linkedList;

linkedList HeadInert()
{
    //头插法
    int x;
    linkedList l,p;
    l=(lNode *)malloc(sizeof(lNode));
    l->next=NULL;
    scanf("%d",&x);
    while (x!=0)
    {
        p=(lNode *)malloc(sizeof(lNode));
        p->data=x;
        p->next=l->next;
        l->next=p;
        scanf("%d",&x);
    }
    return l;
}

linkedList TailInert()
{
    //尾插法
    int x;
    linkedList l,tail,p;
    l=(lNode *)malloc(sizeof(lNode));
    l->next=NULL;
    tail=l;
    scanf("%d",&x);
    while(x!=0)
    {
        p=(lNode *)malloc(sizeof(lNode));
        p->data=x;
        tail->next=p;
        tail=p;
        scanf("%d",&x);
    }
    tail->next=NULL;
    return l;
}

void OutPut(linkedList H)
{
    linkedList p;
    p=H->next;
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}

void Insert(linkedList H,lNode *p,int x)
{
    //插在节点后
    linkedList s;
    s=(lNode *)malloc(sizeof(lNode));
    s->data=x;
    s->next=p->next;
    p->next=s;

}

int main()
{
    //第一种访问方法
    linkedList l=TailInert();
    linkedList visitor=l;
    int x;
    scanf("%d",&x);
    for (int i=0;i<x;i++)
    {
        //访问第x个节点
        visitor=visitor->next;
    }
    printf("The fifth number is: %d\n",(visitor->data));
    // Insert(l,visitor,7);
    //在第五个节点后插入7
    OutPut(l);
    return 0;
}
作者:NorthCity1984
出处:https://grimoire.cn/note/headinsert-tailinsert.html
版权:本文《头插和尾插》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任

Last Modified: May 10, 2020