您好,登錄后才能下訂單哦!
這篇文章主要介紹了C語言中如何實現(xiàn)單向鏈表的增刪查改操作,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
鏈表是線性表的鏈式存儲結構,它可以以O(1)的時間復雜度進行插入或者刪除,同時由于是鏈式結構相比順序表而言,不會存在空間浪費的情況。而鏈表又分為帶頭單向鏈表,不帶頭單向鏈表,帶頭循環(huán)鏈表,不帶頭循環(huán)鏈表,帶頭雙向循環(huán)鏈表,不帶頭雙向循環(huán)鏈表,帶頭雙向鏈表,不帶頭雙向鏈表,總共有八種,其中結構最簡單的是不帶頭單向鏈表,也是實現(xiàn)起來最容易出錯的。并且我們在網(wǎng)上進行鏈表的oj時,題目基本也是不帶頭的單向鏈表,而且也是互聯(lián)網(wǎng)大廠面試中最容易考的。
typedef int SLTDadaType;//存放的數(shù)據(jù)類型 struct SListNode { SLTDadaType _data;//存放的數(shù)據(jù) struct SListNode* _next;//指向下一個節(jié)點的指針 }; typedef struct SListNode SListNode;
SListNode* BuyListNode(SLTDadaType x);//創(chuàng)建一個節(jié)點 SListNode* SListPushBack(SListNode* head, SLTDadaType x);//尾插 SListNode* SListPopBack(SListNode* head);//頭插 SListNode* SListPushFornt(SListNode* head, SLTDadaType x);//尾刪 SListNode* SListPopFornt(SListNode* head);//頭刪 SListNode* SListFind(SListNode* head, SLTDadaType x);//查找一個節(jié)點 void SListModify(SListNode* head, SLTDadaType x,SLTDadaType y);//x修改
SListNode* BuyListNode(SLTDadaType x) { SListNode* newnode = (SListNode*)malloc(sizeof(SListNode)); newnode->_data = x; newnode->_next = NULL; return newnode; }
SListNode* SListPushBack(SListNode* head, SLTDadaType x) { SListNode* newnode = BuyListNode(x);//無論節(jié)點是否為空,都先進行創(chuàng)建一個節(jié)點 if (head == NULL) //頭節(jié)點為空 { head = newnode; return head; } else //頭節(jié)點不為空,直接遍歷到鏈表結尾進行尾插 { SListNode* tail = head; while (tail->_next != NULL) { tail = tail->_next; } tail->_next = newnode; return head; } }
SListNode* SListPushFornt(SListNode* head, SLTDadaType x) { SListNode* newnode = BuyListNode(x); newnode->_next = head; head = newnode; return head; }
SListNode* SListPopBack(SListNode* head) { //1.空 //2.只有一個節(jié)點 //3.有多個節(jié)點 if (head == NULL) { return head; } else if (head->_next== NULL) { free(head); head = NULL; return head; } else { SListNode* prev = NULL; SListNode* tail = head; while (tail->_next != NULL) //利用前指針來保存要刪除的節(jié)點的前一個節(jié)點 { prev = tail; tail = tail->_next; } free(tail); if (prev != NULL) prev->_next = NULL; return head; } }
SListNode* SListPopFornt(SListNode* head) { if (head == NULL) { return head; } else { SListNode* cur = head->_next; free(head); head = cur; return head; } }
SListNode* SListFind(SListNode* head, SLTDadaType x) { SListNode* cur = head; while (cur) { if (cur->_data == x) { return cur; } else { cur = cur->_next; } } return NULL; }
void SListModify(SListNode* head, SLTDadaType x, SLTDadaType y)//x修改 { SListNode* find = SListFind(head, x); if (find) { find->_data = y; } else { printf("對不起,您要修改的值不存在\n"); } }
感謝你能夠認真閱讀完這篇文章,希望小編分享的“C語言中如何實現(xiàn)單向鏈表的增刪查改操作”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。