zoukankan      html  css  js  c++  java
  • 链表-其他基本操作

    单向链表的以下操作:

    创建
    输出
    求表长
    查找值
    插入值
    删除节点

    代码:

    #include <iostream>
    #include <string>
    #include <cmath>
    #include <algorithm>
    using namespace std;
    /*
    创建
    输出
    求表长
    查找值
    追加值(节点) 
    删除节点
    */
    //节点结构体 
    struct Node
    {
        int v;
        Node *next;
    };
    //创建链表 
    Node* create_lian(int n)
    {
        Node *a=new Node,*b;
        b=a;
        cin>>a->v;
        a->next=NULL;
        for(int i=2;i<=n;i++)
        {
            a->next=new Node;
            a=a->next;
            cin>>a->v;
            a->next=NULL;
        }    
        cout<<"Node created."<<endl;
        return b;
    }
    //输出链表 
    void out_lian(Node *p)
    {
        do
        {
            cout<<p->v<<endl;
            p=p->next;
        }
        while(p!=NULL);
    }
    //求表长
    int lian_len(Node *p)
    {
        int c=0;
        while(p!=NULL)
        {
            c++;
            p=p->next;
        }
        return c;
    }
    //查找值所在的位置 
    int lian_search(Node *x,int y)
    {
        int p=0;
        while(x!=NULL)
        {
            p++;
            if(x->v==y)
            {
                return p;
            }
            x=x->next;
        }
        return p;
    }
    //追加值(节点)
    void lian_append(Node *x,int y)
    {
        //准备待追加的节点 
        Node t;//此处使用变量,在多次添加的时候会出现内存重复的问题。使用new申请空间可以解决。
        t.v=y;
        t.next=NULL;
        //找到链表的结尾节点 
        while(x->next!=NULL)
        {
            x=x->next;
        }
        //追加
        x->next=&t; 
    }
    //删除值(节点)因为可能第一个点就是要删除的值,必须返回新链表的首地址。 
    Node* lian_del(Node *x,int y)
    {
        Node *head=x,*pre;
        //处理要删除的元素(连续)打头的情况 
        while(x->v==y&&x!=NULL)
        {
            head=x->next;
            free(x);
            x=head;
        }
        pre=head;
        x=head->next;
        while(x!=NULL)
        {
            if(x->v==y)
            {
                pre->next=x->next;
                free(x);
                x=pre->next;
            }
            else
            {
                pre=x;
                x=x->next;
            }
        }
        return head;
    }
    main()
    {
        int n,x;
        Node *head;
        cin>>n;
        head=create_lian(n);
        /*//显示节点数
        cout<<lian_len(head)<<endl;
        //查找x所在的位置
        cin>>x;
        cout<<lian_search(head,x);
        //在链表结尾追加值(节点) 
        cin>>x;
        lian_append(head,x);*/
        //从链表中删除值
        cin>>x;
        head=lian_del(head,x);
        out_lian(head); 
    }

    end here

  • 相关阅读:
    .NET简谈设计模式之(适配器模式)
    .NET简谈组件程序设计之(手动同步)
    .NET简谈组件程序设计之(初识远程调用)
    .NET简谈组件程序设计之(初识.NET线程Thread)
    .NET映射设计(Model与UIControl之间的模型关系)
    .NET简谈事务本质论
    .NET简谈组件程序设计之(异步委托)
    向5.4致敬吧 无为而为
    SQL 2005 分析服务基于角色的动态授权 无为而为
    文思创新深圳招聘biztalk 无为而为
  • 原文地址:https://www.cnblogs.com/wanjinliu/p/11409997.html
Copyright © 2011-2022 走看看