用类实现链表:
#include<iostream>
using namespace std;class List
{struct Node{int Nval;Node* pNext;};
private:Node* pHead = NULL;Node* pEnd = NULL;
public:void AddNode(int n);void DelNode(int n);void walk();
};
void List::AddNode(int k)
{Node* ptemp = new Node;ptemp->Nval = k;ptemp->pNext = NULL;if (NULL == pHead){pHead = ptemp;}else{pEnd->pNext = ptemp;}pEnd = ptemp;
}
void List::DelNode(int n)
{Node* pdel = NULL;if (pHead->Nval == n){pdel = pHead;pHead = pHead->pNext;free(pdel);pdel = NULL;return;}Node* pmark = pHead;while (pmark->pNext != NULL){if (pmark->pNext->Nval == n){pdel = pmark->pNext;pmark->pNext = pmark->pNext->pNext;free(pdel);pdel = NULL;if (pmark->pNext == NULL){pEnd = pmark;}return;}pmark = pmark->pNext;}
}
void List::walk()
{while (pHead != NULL){cout << pHead->Nval << endl;pHead = pHead->pNext;}
}int main()
{List list;list.AddNode(1);list.AddNode(2);list.AddNode(3);list.DelNode(1);list.DelNode(2);list.walk();return 0;
}
用类实现队列:
#include<iostream>
using namespace std;class Queue
{struct Node{int Nval;Node* pNext;};
private:Node* pHead = NULL;Node* pEnd = NULL;
public:void Push(int n);int pop();};
void Queue::Push(int n)
{Node* pTemp = new Node;pTemp->Nval = n;pTemp->pNext = NULL;if (pHead == NULL){pHead = pTemp;}else{pEnd->pNext = pTemp;}pEnd = pTemp;
}
int Queue::pop()
{if (pHead != NULL){Node* pdel = pHead;pHead = pHead->pNext;int n = pdel->Nval;free(pdel);pdel = NULL;if (NULL == pHead){pEnd = NULL;}return n;}return -1;
}int main()
{Queue yan;yan.Push(1);yan.Push(2);yan.Push(3);cout << yan.pop() << endl;cout << yan.pop() << endl;cout << yan.pop() << endl;return 0;
}
用类实现栈:
#include<iostream>
using namespace std;class List
{struct Node{int n;Node* pnext;};
private:Node* ptop = NULL;
public:void push(int n);int pop();
};
void List::push(int n)
{Node* ptemp = new Node;ptemp->n = n;ptemp->pnext = NULL;if (ptop != NULL){ptemp->pnext = ptop;ptop = ptemp;}else{ptop = ptemp;}
}
int List::pop()
{if (ptop != NULL){Node* pdel = ptop;ptop = ptop->pnext;int k = pdel->n;free(pdel);pdel = NULL;return k;}return -1;
}int main()
{List k;k.push(1);k.push(2);k.push(3);cout << k.pop()<< endl;cout << k.pop() << endl;cout << k.pop() << endl;return 0;
}