zoukankan      html  css  js  c++  java
  • *循环单链表[带头结点]

    结构:

    判空:(head->next==head)

    初始化:主要注意链表为空的条件,执行语句:L->next=L;

    void InitList(List &L)/*初始化空表*/
    {
        L=(List)malloc(sizeof(Node));/*生成头结点*/
        L->next=L;/*判空的条件*/
    }

    创建:借助一个游标p进行移动、

    void creat(List &head,int n)/*创建*/
    {
        int e;
        List p,s;
        p=head;
        while(n>0)
        {
            cin>>e;
            s=(List)malloc(sizeof(Node));
            s->data=e;
            p->next=s;
            s->next=head;
            p=s;
            --n;
        }
    }

    插入:在第i个位置处插入e,先把指针移到i-1处,然后进行操作。此外,p从头结点开始移动。

    void Insert(List &L,int i,int e)
    {
        List p,s;
        p=L;/*p等于头结点*/
        while(i-1>0)/*移动到第i个位置之前,需要移动i-1次*/
        {
            p=p->next;
            i--;
        }
        s=(List)malloc(sizeof(Node));
        s->data=e;
        
        s->next=p->next;
        p->next=s;
    }

    删除:将第i个元素删除。借助两个游标s,p,将p移动到i位置,s同步移动到i-1处,两者配合操作。p从头结点处开始,需要移动i次!

    void Delete(List &L,int i)
    {
        List s,p;
        p=L;
        while(i>0)
        {
            s=p;
            p=p->next;
            i--;
        }
        s->next=p->next;
        free(p);
    }

    完整代码:

    #include <iostream>
    using namespace std;
    typedef struct node
    {
        int data;
        struct node *next;
    }*List,Node;
    
    void InitList(List &L)/*初始化空表*/
    {
        L=(List)malloc(sizeof(Node));/*生成头结点*/
        L->next=L;/*判空的条件*/
    }
    void creat(List &head,int n)/*创建*/
    {
        int e;
        List p,s;
        p=head;
        while(n>0)
        {
            cin>>e;
            s=(List)malloc(sizeof(Node));
            s->data=e;
            p->next=s;
            s->next=head;
            p=s;
            --n;
        }
    }
    void Traverse(List &head)/*遍历*/
    {
        List p=head->next;
        while(p!=head)
        {
            cout<<p->data<<" ";
            p=p->next;
        };
    }
    void Destory(List &L)/*销毁*/
    {
        List p,q;
        p=L->next;
        while(p!=L)
        {
            q=p;
            p=p->next;
            free(q);
        }
        L->next=L;
    }
    int main()
    {
        List L;
        InitList(L);
        creat(L,3);
        print(L);
        destory(L);
        return 0;
    }
  • 相关阅读:
    好文章集合
    WPF:布局
    xcode6.0 模拟器打不开
    vue-vux初学
    【个人笔记】《知了堂》MySQL三种关系:一对一,一对多,多对多。
    vue-axios跨域配置
    vue+webpack使用
    vs code插件
    echarts图表属性设置
    【个人笔记】《知了堂》ajax的get及post请求
  • 原文地址:https://www.cnblogs.com/tinaluo/p/5240727.html
Copyright © 2011-2022 走看看