链表实现
#include <iostream> #include <cstdlib> using namespace std; struct LNode{ int data; LNode* next; }; typedef LNode* LinkedList; void creatLinkList(LinkedList &L){ L= (LinkedList)malloc(sizeof(LNode)); L->data=0; L->next=NULL; int x; cout<<"请输入链表长度:"; cin>>x; for (int i=0;i<x;i++) { int tmp; cin>>tmp; LinkedList t = (LinkedList)malloc(sizeof(LNode)); t->data=tmp; t->next=L->next; L->next=t; } } void creatLinkList2(LinkedList &L){ L=(LinkedList)malloc(sizeof(LNode)); L->data=0; L->next=NULL; LinkedList r=L; int n; cout<<"请输入:"; cin>>n; for (int i=0;i<n;i++) { int tmp;cin>>tmp; LinkedList q = (LinkedList)malloc(sizeof(LNode)); q->data=tmp; q->next=NULL; r->next=q; r=q; } } void printLinkedList(LinkedList L){ LinkedList p = L->next; while (p) { cout<<p->data<<" "; p=p->next; } cout<<endl; } void reverseLinkedList(LinkedList &L){ LinkedList p,q; p=L->next; L->next=NULL; while (p) { q=p; p=p->next; q->next=L->next; L->next=q; } } int main(){ LinkedList L; creatLinkList2(L); printLinkedList(L); reverseLinkedList(L); printLinkedList(L); return 0; }
二叉树
#include <iostream> using namespace std; #define MAX(a,b) (a>b)?a:b struct BiNode { char data; BiNode* lchild; BiNode* rchild; }; typedef BiNode* BiTree; int heightBiTree(BiTree T){ if(T == NULL) return 0; else{ return MAX(heightBiTree(T->lchild),heightBiTree(T->rchild))+1; } } int countBiTree(BiTree T) { if(T == NULL) { return 0; } else{ return countBiTree(T->lchild)+countBiTree(T->rchild)+1; } } void preOrder(BiTree T) { if(T==NULL) return; cout<<T->data<<" "; preOrder(T->lchild); preOrder(T->rchild); } void inOrder(BiTree T) { if(T==NULL) return; inOrder(T->lchild); cout<<T->data<<" "; inOrder(T->rchild); } void lastOrder(BiTree T) { if(T==NULL) return; lastOrder(T->lchild); lastOrder(T->rchild); cout<<T->data<<" "; } int main(int argc, char *argv[]) { return 0; }