Cracking The Coding Interview 2.0 单链表
2014-04-08 11:10
411 查看
#include <iostream> #include <string> using namespace std; class linklist { private: class node { public: node(){} string data; node * next; }; node *first; int size; public: linklist() { first = new node; size = 0; } /***整表创建***/ void Create(string *s,int size) { if (s==NULL || size == 0) { return; } node *p = new node; p->data = s[0]; first->next = p; for (int i = 1; i<size; i++) { node *t = new node; t->data = s[i]; p->next = t; p=p->next; } p->next = NULL; this->size = size; } /***整表删除***/ void Clear() { for (int i = 1;i<size+1; i++) { Delete(i); } first = NULL; size = 0; } /***第i[i为1,2....size,下同]个元素前插入string型e***/ void Insert(int i, string e) { if (i<0 || i>size) { return; } int t = i - 1; node *p = first; node *pn = p->next; while(t!=0) { p = p->next; pn = pn->next; t--; } node *ee = new node; ee->data = e; ee->next = pn; p->next = ee; size ++; } /****获取第i个元素的值,并返回该值**/ string Get(int i) { if (i<=0 || i>size) { return "Error: You input wrong num."; } int t = i; node *p =first; while(t!=0) { p = p->next; t--; } return p->data; } /***删除第i个元素***/ void Delete(int i) { if (i<0 || i>size) { return; } int t = i - 1; node *p = first; node *pn = p->next; while(t!=0) { p = p->next; pn = pn->next; t--; } p->next = pn->next; delete pn; size --; } void Display() { if (first==NULL) { return; } node * p; p=first->next; /*for (int i =0; i<size; i++) { cout<<p->data<<" "; p=p->next; }*/ while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } ~linklist() { } }; int main() { string str[3]={"sos","OMG","fof"}; linklist s; s.Create(str,3); s.Display(); s.Insert(2,"bingo"); s.Display(); s.Delete(3); s.Display(); cout<<s.Get(1)<<endl; s.Clear(); s.Display(); return 0; }
相关文章推荐
- Cracking the coding interview--Q17.4
- Cracking the coding interview--Q1.4
- Cracking the coding interview--Q9.3
- Cracking the coding interview--Q1.7
- Cracking the coding interview--Q2.1
- Cracking the coding interview--Q19.2
- Cracking the coding interview--Q19.4
- 【Cracking the coding interview】Q1.2(反转字符串)
- Cracking the Coding Interview(linked list)
- 渣基础:比照Hawstein学Cracking the coding interview(2)
- Cracking The Coding Interview 4.2_暂存
- Cracking the coding interview--Q1.3
- 《Cracking the coding interview》
- [Cracking the Coding Interview] Chapter 3 - Stacks and Queues
- 《Cracking the Coding Interview》——第13章:C和C++——题目5
- Cracking the coding interview--Q2.1
- Cracking the coding interview 第一章问题及解答
- Cracking the coding interview--Q17
- CRACKING THE CODING INTERVIEW 笔记(1)
- 《Cracking the Coding Interview》——第17章:普通题——题目6