單鏈表,單鏈表的基本操作
大神請繞過
/****************\* 單鏈表C++實現* Created by Satan* Time:2015年1月28號\****************/#include<iostream>using namespace std;//儲存節點的結構體struct listElmt{int data;//存放資料listElmt * next;//指向下一個元素listElmt(int tmp){this->data = tmp;this->next = NULL;}};//鏈表類class List{private:listElmt * head;//前端節點指標listElmt * tail;//尾節點指標int length;//鏈表長度public:/**********************\*建構函式,初始化鏈表\**********************/List(){this->head = NULL;this->tail = NULL;this->length = 0;}/***********************\*參數:資料地址*傳回值:插入元素成功則返回true,否則返回false*描述:在鏈表尾部插入一個新的節點,節點的資料為參數傳入的資料。如果此時鏈表為空白,*則將頭指標和尾指標同時指向該節點,不為空白則將尾指標指向該節點\***********************/bool insert(int data){int priorLength = this->length;//記錄操作之前的鏈表長度listElmt * newElmt = new listElmt(data);if(this->length == 0){//如果鏈表為空白,則將頭、尾指標指向該節點this->head = newElmt;this->tail = newElmt;this->length++;}else{this->tail->next = newElmt;this->tail = this->tail->next;this->length++;}return bool(this->length - priorLength);}/**********************\*參數:資料地址*傳回值:刪除掉的元素的個數*描述:從鏈表中刪除所有與指定資料相同的元素。如果被刪除的是前端節點,則頭指標指向前端節點之後的那個節點;*如果刪除的是中間節點,則該節點的前一個節點應該指向該節點的後一個節點;如果刪除的是尾節點,*則尾指標應該指向尾節點的前一個節點\**********************/int remove(int data){listElmt * currentElmt = this->head;//遍曆鏈表時當前指向的節點int count = 0;//刪除的節點個數if(currentElmt){return count;}if(currentElmt->data == data){//如果刪除前端節點,頭指標向後移this->head = currentElmt->next;count++;delete(currentElmt);}while(currentElmt->next != NULL){//遍曆前端節點之後的節點if(currentElmt->next->data == data){listElmt * tmpElmt = currentElmt->next;//臨時存放將要被刪除的節點if(tmpElmt->next == NULL){//如果刪除尾節點,尾指標前移currentElmt->next = NULL;this->tail = currentElmt;}else{//如果刪除中間節點currentElmt->next = tmpElmt->next;}count++;delete(tmpElmt);}}return count;}/*************************\*參數:資料地址*傳回值:若找到元素則返回true,否則返回false*描述:遍曆鏈表,尋找資料與參數資料相同的節點\*************************/bool contains(int data){listElmt * currentElmt = this->head;if(currentElmt == NULL){//鏈表為空白return false;}do{//從前端節點開始遍曆鏈表if(currentElmt->data == data){return true;}}while(currentElmt = currentElmt->next);//當前節點指向尾節點之後則跳出迴圈return false;}/**********************\*參數:void*傳回值:void*描述:遍曆鏈表,列印出所有節點中儲存的資料\**********************/void print(){listElmt * currentElmt = this->head;if(currentElmt == NULL){return;}do{cout << currentElmt->data << '\n';}while(currentElmt = currentElmt->next);}/*************************\*參數:void*傳回值:鏈表長度*描述:返回鏈表長度\*************************/int getLength(){return this->length;}/************************\*解構函式,銷毀鏈表\************************/~List(){listElmt * currentElmt = this->head;listElmt * nextElmt;do{nextElmt = currentElmt->next;delete(currentElmt);}while(currentElmt);}};