链表就不进行说明了,直接上模板
单链表的结点模板template链表类示例class Node { private: Node *next; public: T data; // 理论放到 private Node(const T& item, Node *next = 0); void insertAfter(Node *p); Node *deleteAfter(); Node *nextNode() const; }; template Node ::Node(const T& data, Node *next = 0):data(data), next(next) {} template Node *Node ::nextNode() { return next; } template void Node ::insertAfter(Node *p) { p->next = next; next = p; } template Node *Node ::deleteAfter(void) { // 删除操作还要返回是有时需要继续操作删除的结点 Node *tempPtr = next; if(next == 0) return 0; next = tempPtr->next; return tempPrt; }
使用 STL 库的链表类模板
从键盘输入 10 个整数,用这些整数生成一个链表,按顺序输出链表中结点的数值。
输入一个待查找整数,在链表中查找该整数,删除所在结点,输出链表
程序结束时清空链表
#include#include "LinkedList.h" using namespace std; int main() { LinkedList list; // 1 for(int i=0; i<10; i++) { int item; cin >> item; list.insertFront(item); } cout << "List : "; list.reset(); while(! list.endOfList() ) { cout << list.data() << " "; list.next(); } cout << endl; // 2 int key; cout << "Please enter some integer neeeded to be deleted: "; cin >> key; list.reset(); while(! list.endOfList() ) { if(list.data() == key) list.deleteCurrent(); list.next(); } cout << "list : "; // 3 list.reset(); while(! list.endOfList() ) { cout << list.data() << " "; list.next(); } cout << endl; return 0; }



