C 鍊錶的建立和插入刪除的實現

2021-07-11 13:25:24 字數 1969 閱讀 9847

使用c++建立鍊錶一直是很頭疼的事,建立鍊錶為了後面的操作方便,我們需要返回頭指標,有了頭指標就可以做後面的操作了,比如顯示列表,增刪改查等等,在create函式裡首先申明兩個指標,乙個是用來儲存上乙個節點的位址p2,乙個用來儲存新建立節點的位址p1,當我們只建立了乙個節點是,那麼此時head指標和p1, p2都指向了這乙個節點,也就是他們儲存的位址是一樣的,如果乙個節點也沒建立呢,就是將新建立出節點的位址p1刪除掉,p2設定為空,p2的next設定為空,head設定為空,並且返回head指標,此時相當於什麼也沒操作;當建立兩個以上的節點時,就是將上乙個節點的next指向新節點,p2->next = p1; p2 = p1;這樣迴圈往復的使用,知道出現圖書編號為零的情況,那麼此時將新建立的節點p1刪掉,將p2->next = null即可,同時返回頭指標,這樣三種建立情況都有了。同時裡面有個check字串的函式,如果是字串的那麼直接就推出了,必須是數字才行,於是有用到了c++標準庫函式atoi,atof,在code::blocks裡要想用這兩個函式必須#include 和這兩個庫才行。

建立好了,就要顯示我們建立的列表了,只需要王函式裡傳遞鍊錶的頭指標就行,以此head表示當前節點,head->next表示下乙個節點,以此顯示他們的標號和**就行。

刪除節點分兩種情況,一種是刪除頭節點,那麼將頭指標指向下乙個節點就行,如果是刪除中間的節點,需要將要刪除節點的前乙個節點的next指向要刪除節點的下乙個節點就行了,然後再head = head->next這裡的head表示的是當前節點,不是頭節點。

插入節點,往頭部插,尾部插,中間插幾種情況,頭部的話就是將head指標指向新節點,新節點的next指向原來的頭節點,尾部的話就是將原來的尾節點的next指向新節點,新節點的next設定為null即可,關鍵是中間節點的插入,就是將前乙個節點的next指向新節點,新節點的next指向原來節點的下乙個節點,具體**如下:

#include #include #include #include using namespace std;

class book

;book *head = null;

bool check(string str)

return true;

}book *create()

p1 -> num = atoi(str.c_str());

if(p1 -> num != 0)

p1 -> price = atof(str.c_str());

}else

while(p1->num != 0)

p1 -> num = atoi(str.c_str());

if(p1 -> num != 0)

p1 -> price = atof(str.c_str());

}p2 -> next = p1;

}delete p1;

p2 -> next = null;

return head;

}void showbook(book *head)

}void deletebook(book *head, int num)

while(head)

if(head -> next -> num == num)

head = head -> next;

}cout << "not found num" << endl;

}void insertbook(book *head, int num, float price)

l -> next = p;

p -> next = null;

}void insertheadbook(book *head, int num, float price)

book *temp = null;

while((num > head -> num) && (head -> next != null))

if(num > head -> num)

else

}int main()

c 實現鍊錶建立 插入 刪除

使用類模板設計的鍊錶建立 插入 刪除操作。類模板不懂的,可以看下我的template簡單介紹 建立鍊錶實際就是將struct結構體或者class類物件連線在一起 鍊錶插入如圖示 使用的是頭插法 鍊錶刪除操作 上 include include include include using namesp...

C語言實現順序鍊錶的建立和刪除插入元素

include include define len sizeof struct student 順序鍊錶的建立 刪除 插入操作 struct student int n struct student creat else p2 p1 p1 struct student malloc len pri...

鍊錶的建立和刪除,初識鍊錶

include include include typedef struct date 申明結構體 date int main void else pe next ps 把新結點連線到鏈尾 第一次不執行,而到第二次pe就是上一次的ps 而pe next讓其指向下一次的ps pe ps 新結點成為了新...