请你定义一个链表,可以对链表进行“在某个元素之前插入一些元素”、“删除某个位置的元素”、“查找某元素”、“获取某个位置的元素”、“遍历输出所有元素”、“求链表的长度”等操作。键盘输入一些命令,可以执行上述操作。本题中,链表元素为整数,链表的第一个元素位置为1,链表的最大长度为20。
#include using namespace std;
struct Node { int data; Node *next; };
class Linklist { public: Linklist(); int length(); void Insert(int i, int x); void Get(int i); void Locate(int x); void Delete(int i); void Printlist(); private: Node *first; };
Linklist::Linklist() { first = new Node; first->next= NULL; }
void Linklist::Printlist() { Node *p = first->next; while(p != NULL) { cout << p->data; p = p->next; } }
int Linklist::length() { Node *p = first->next; int count = 0; while (p != NULL) { p = p->next; count++; } return count; }
void Linklist::Get(int i) { Node *p = first; int count = 0; while (p != NULL && count < i) { p = p->next; count++; } if (p == NULL) { cout << “位置不正确” << endl; } else { cout << p->data << endl; } }
void Linklist::Locate(int x) { Node * p = first->next; int count = 1; while (p != NULL) { if (p->data == x) { cout << count; return; } p = p->next; count++; } if (p == NULL) { cout << “None” << endl; } }
void Linklist::Insert(int i,int x) { Node *p = first,*s = NULL; int count = 0; s = new Node; while (p != NULL && count < i-1) { p = p->next; count++; } s->data = x; s->next = p->next; p->next = s; }
void Linklist::Delete(int i) { int x; Node *p = first; Node *s = NULL; int count = 0; while (p != NULL && count < i-1) { p = p->next; count++; }
s = p->next; x = s->data; p->next = s->next; delete s; cout << x;}
int main() { Linklist L; int k,x,num; char c; while (1) { cin >> c; if (c == ‘E’) { break; } switch© { case ‘I’: { cin >> num; for (int i = 0; i < num; i++) { cin >> k >> x; L.Insert(k,x); } } break; case ‘S’: cin >> k; L.Locate(k); break; case ‘D’: cin >> k; L.Delete(k); break; case ‘G’: cin >> k; L.Get(k); break; case ‘L’: cout << L.length(); break; case ‘V’: L.Printlist(); break; } } }