广义表(2)

 

计算广义表原子结点个数

 

public int CountAtom()
{
    return CountAtom(_Root);
}

public int CountAtom(GLNode<char> node)
{
    int i = 0;
    if (node != null)
    {
        switch (node.Type)
        {
            case NodeType.Atom:
                i++;
                break;
            case NodeType.List:
                i+=CountAtom(node.Item as GLNode<char>);
                break;
        }
        
        return i + CountAtom(node.Next);
    }
    return 0;
}

 

替换相同原子

 

public void Replace(char oldchar, char newchar)
{
    Replace(_Root, oldchar, newchar);
}

public void Replace(GLNode<char> node,char oldchar,char newchar)
{
    if (node != null)
    {
        switch (node.Type)
        {
            case NodeType.Atom:
                if ((char)node.Item == oldchar)
                    node.Item = newchar;
                break;
            case NodeType.List:
                Replace(node.Item as GLNode<char>, oldchar, newchar);
                break;
        }

        Replace(node.Next,oldchar,newchar);
    }
}

 

删除相同原子

 

public GLNode<char> DeleteAtom(char key)
{
    return DeleteAtom(_Root, key);
}

public GLNode<char> DeleteAtom(GLNode<char> node, char key)
{
    GLNode<char> current = node;
    if (current != null)
    {
        switch (current.Type)
        {
            case NodeType.Atom:
                if ((char) current.Item == key)
                    return DeleteAtom(current.Next, key);
                break;
            case NodeType.List:
                DeleteAtom(current.Item as GLNode<char>, key);
                break;
        }
        current.Next = DeleteAtom(current.Next, key);
        _Root = current;
        return current;
    }
    return null;
}

 

广义表逆置

将头与尾交换,如a,b,c

则a与b,c;b与c交换,也是一个递归过程从尾交换开始,

public GLNode<char> Reverse(GLNode<char> node)
{
    if (IsEmpty(node)) return null;

    switch (node.Type)
    {
        case NodeType.Atom:
            if (node.Next != null)
                node = Append(Reverse(GetTail(node)), GetHead(node));
            break;
        case NodeType.List:
            node = Append(Reverse(GetTail(node)), new GLNode<char>() { Item = Reverse((GLNode<char>)node.Item), Type = NodeType.List });
            break;
    }

    return node;
}

public GLNode<char> Append(GLNode<char> head, GLNode<char> tail)
{
    if (IsEmpty(head)) return tail;

    var pre = head;
    var cur = head.Next;

    while (cur != null)
    {
        pre = cur;
        cur = cur.Next;
    }

    pre.Next = tail;

    return head;
}

 

判断两个广义表是否完全相等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值