[C++] Linking List 范例代码

前阵子公司有新人员要来面试,Boss要我出一些题目,就随手出了一些题目

这是其中一题Linking List的解答.

题目1:请写出单向串列链结

题目2:请写出反转的演算法

 

// LinkList.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; template <typename T> struct MyNode { T id; MyNode * next; MyNode(T _id) { id = _id; next = NULL; } }; template <typename T> class MyList { MyNode<T> * head; MyNode<T> * current; public: MyList() : head(NULL) {} void add(T value) { MyNode<T>* node = new MyNode<T>(value); if(head == NULL) { head = node; current = head; } else { current->next = node; current = node; } } void showAll() { MyNode<T> *go = head; while(go != NULL) { cout<<go->id<<endl; go = go->next; } } void reverse() { MyNode<T> *preNode = NULL; MyNode<T> *currentNode = head; MyNode<T> *nextNode = head->next; while(true) { nextNode = currentNode->next; currentNode->next = preNode; preNode = currentNode; currentNode = nextNode; if(currentNode->next == NULL) { head = currentNode; head->next = preNode; break; } } } }; int _tmain(int argc, _TCHAR* argv[]) { MyList<int> *list = new MyList<int>(); list->add(123); list->add(456); list->add(789); list->showAll(); list->reverse(); cout<<"after reverse:"<<endl; list->showAll(); system("pause"); return 0; }

你可能感兴趣的:([C++] Linking List 范例代码)