计算广义表原子结点个数
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; }