Cracking The Coding Interview 2.2
2014-04-08 21:24
375 查看
#include <iostream> #include <string> using namespace std; class linklist { private: class node { public: node(){} string data; node * next; }; node *head; int size; public: linklist() { head = new node; size = 0; } /***整表创建***/ void Create(string *s,int size) { if (s==NULL || size == 0) { return; } node *p = new node; p->data = s[0]; head->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); } head = 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 = head; 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 =head; 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 = head; node *pn = p->next; while(t!=0) { p = p->next; pn = pn->next; t--; } p->next = pn->next; delete pn; size --; } void Display() { if (head==NULL) { return; } node * p; p=head->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() { } /*****Implement an algorithm to find the nth to last element of a singly linked list.*****/ string GetLastN(int n) { if (n<0||n>size) { return "Error: Wrong Number"; } int i = 0; node *p = head->next; node *q = head->next; while(i<n) { p=p->next; i++; } while(p!=NULL) { p=p->next; q=q->next; } return q->data; } }; int main() { string str[8]={"sos","OMG","sos","OMG","OMG","OMG","fof","fof"}; linklist s; s.Create(str,8); s.Display(); /*s.Insert(2,"bingo"); s.Display(); s.Delete(3); s.Display(); cout<<s.Get(1)<<endl; s.Clear(); s.Display();*/ //s.RemoveDupulicate(); cout<<s.GetLastN(6); //s.Display(); return 0; }
相关文章推荐
- Cracking the Coding Interview Q2.2
- Cracking the coding interview--Q2.2
- Cracking the Coding Interview 8.7
- Cracking the coding interview--Q4.5
- Cracking the coding interview--Q8.4
- Cracking the coding interview--Q5.7
- Cracking the coding interview--Q1.6
- Cracking the coding interview--Q1.4
- Cracking the coding interview--Q9.7
- 《Cracking the Coding Interview》——第2章:链表——题目2
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目3
- Cracking the Coding Interview Q2.6
- cracking the coding interview No1.1
- cracking the coding interview No1.6
- Cracking the coding interview--Q19.3
- Cracking the coding interview--Q1.2
- Cracking the coding interview--Q1.8
- cracking the coding interview ch1.1
- cracking the coding interview ch1.2