【資料結構】單鏈表的實現與基本操作C++
阿新 • • 發佈:2019-01-22
最近在複習資料結構,自己用C++寫了單鏈表這一塊的一些程式碼。
以下是帶頭結點單鏈表的建立和查詢等的程式碼。
#include <iostream> using namespace std; //單鏈表 struct LNode{ int data; struct LNode *next; }; //建立一個帶頭結點的單鏈表,採用頭插法 LNode* createLNode(){ LNode *head = (LNode *)malloc(sizeof(LNode)); head->next = NULL; LNode *newNode; int data; int x = 0; cout<<"begin input:"<<endl; cout<<"The number of List:"; int num; cin>>num; while(x < num){ cin>>data; newNode = (LNode *)malloc(sizeof(LNode)); newNode->data = data; newNode->next = head->next; head->next = newNode; x++; } return head; } //建立單鏈表,後插法,帶頭結點 LNode* createLNode_back(){ LNode *head = (LNode *)malloc(sizeof(LNode)); //頭指標 head->next = NULL; LNode *newNode; cout<<"begin input:"<<endl; cout<<"The number of List:"; int num; cin>>num; LNode *tail = head; int x = 0; while(x < num){ newNode = (LNode *)malloc(sizeof(LNode)); cin>>newNode->data; tail->next = newNode; tail = newNode; x++; } tail->next = NULL; return head; } //列印單鏈表 void printLNode(LNode *list){ while(list->next != NULL){ list = list->next; cout<<list->data<<" "; } cout<<endl; } //新增元素 void addElem(LNode *list, int data){ LNode *newNode = (LNode *)malloc(sizeof(LNode)); newNode->data = data; newNode->next = list->next; list->next = newNode; cout<<"add success!"<<endl; } //刪除元素,根據索引刪除 bool removeElem(LNode *list, int index){ LNode *point = list->next; if(index < 0){ cout<<"index is ERROR!"; return false; } int i = 0; //找到刪除節點的前驅節點 while(i != index-1){ cout<<i<<" "; if(point->next == NULL){ cout<<"index is ERROR!"; return false; } point = point->next; i++; } //刪除節點 list->next = list->next->next; return true; } void main(){ LNode *list; list = createLNode_back(); printLNode(list); }