MENU

头插和尾插

April 7, 2020 • Read: 284 • 笔记

/*
 * @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;
}
Last Modified: May 10, 2020
Archives Tip
QR Code for this page
Tipping QR Code