1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| #include<stdlib.h> #include<iostream> class node{ public: int data; node *next; node(){ data = -1; next = NULL; } node(int data,node *next){ this->data = data; this->next = next; } };
class List{ private: node* head; int lenth; bool check(int index); public: int size(){return lenth+1;} List(); List(const List& temp); ~List(); void append(const int num); void insert(int index,int num); void delnum(int index); void clear(); void combine(int index,const List& temp); int& operator[](int index); int search(int aim); void show(); };
bool List::check(int index){ if(index<0||index>lenth){ std::cout << "INDEX_ERROR" << std::endl; return false; } return true; }
List::List(){ head = new node; lenth = -1; }
List::List(const List& copy){ node* p1 = head; node* p2 = copy.head->next; while(p2!=NULL){ p1->next = new node(p2->data,NULL); p1 = p1->next; lenth++; p2 = p2->next; } }
List::~List(){ node* p1; node* p2 = head; while(p2->next!=NULL){ p1 = p2; p2 = p2->next; delete p1; } delete p2; }
void List::append(const int num){ node* p = head; while(p->next!=NULL) p=p->next; p->next = new node(num,NULL); lenth++; }
void List::insert(int index,int num){ if(index<0||index>lenth+1){ std::cout << "INDEX_ERROR" << std::endl; return; } node* p1 = head; node* p2 = new node(num,NULL); for(int i=0;i<index;i++) p1 = p1->next; p2->next = p1->next; p1->next = p2; lenth++; }
void List::delnum(int index){ if(!check(index)) return; node* p1 = head; node* p2; for(int i=0;i<index;i++) p1 = p1->next; p2 = p1->next; p1->next = p2->next; delete p2; lenth--; }
void List::clear(){ node* p1; node* p2 = head->next; while(p2->next!=NULL){ p1 = p2; p2 = p2->next; delete p1; } delete p2; head->next = NULL; lenth = 0; }
void List::combine(int index,const List& inserted){ if(!check(index)) return; node* p1 = head; node* p2 = inserted.head->next; for(int i=0;i<index;i++) p1 = p1->next; while(p2!=NULL){ node* temp = new node(p2->data,p1->next); p1->next = temp; p2 = p2->next; lenth++; } }
int& List::operator[](int index){ if(!check(index)) return this->head->data; node* p = this->head; for(int i=0;i<=index;i++) p=p->next; return p->data; }
int List::search(int aim){ node* p = head->next; int ans = 0; while(p!=NULL && p->data!=aim){ p = p->next; ans++; } if(p==NULL) return -1; return ans; }
void List::show(){ node* p = head->next; while(p!=NULL){ std::cout << p->data << " "; p = p->next; } std::cout << std::endl; }
|