建立单链表——头插法 和 尾插法

因为markdown编译能力有限 ,暂时上图片吧,我觉得也挺方便的

又在为自己菜找借口了

我看着自己画的图就把代码敲出来了,不算难。

注意:实现了链栈的入栈之后,我发现这张图画的不是特别准确,表头是不动的,一直是在表头与第一个节点之间插入新的节点!

 

建立单链表——头插法 和 尾插法_第1张图片

 

上代码:

#include
#include
using namespace std;
struct node
{
    int data;
    node *nex;
};
void head_in(node *a)/*头插法*/
{
    node *head=a;
    int x;
    while(1)
    {
        scanf("%d",&x);
        if(x==-1)
            return ;
        node *q=new node;
        q->data=x;

        q->nex=head->nex;/*新节点不断接到链表的头部*/
        head->nex=q;/*head->next指向的永远是链表的头*/
    }
}
void tail_in(node *a)/*尾插法*/
{
    node *tail=a;
    int x;
    while(1)
    {
        scanf("%d",&x);
        if(x==-1)
            break;
        node *q=new node;
        q->data=x;
        q->nex=NULL;/*尾部就要是NULL*/

        tail->nex=q;/*在尾巴上接一个q (新节点)*/
        tail=q;/*q 当作尾巴*/
    }
    return ;
}
void visit(node *head)
{
    node *p=head->nex;
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->nex;
    }
    printf("\n");
    return ;
}
int main()
{
    node *a=new node;
    a->nex=NULL;
    head_in(a);
    visit(a);

    node *b=new node;
    b->nex=NULL;
    tail_in(b);
    visit(b);
    return 0;
}

 

你可能感兴趣的:(数据结构)