單向鍊錶 尾插法

2021-10-05 07:16:54 字數 1281 閱讀 3787

#include

#include //malloc函式標頭檔案

//1設計節點(放置資料和指標)不同資料用結構體

//結構體模板

struct node

; //關鍵字 結構體模板名稱 指標名字

//struct node next ; next為結構體變數,如此定義會陷入死迴圈

//定義乙個函式,初始化鍊錶,棧空間,函式呼叫後返回乙個head指標,隨後釋放

struct node* init_list(void)

head->next = null;

return head;

}//建立新節點(帶資料和指標),呼叫新函式

struct node* new_node(int data)

//資料存入節點當中

new->data = data;

new->next = null;

return new;
//將新節點插入到鍊錶末尾(尾插法)

int tail_ins(struct node head,struct node new)

//鍊錶遍歷

void show(struct node head)

int main(void)

//堆裡面新建鍊錶並初始化,頭指標在棧中,指向頭節點

struct node* head=init_list();

if(head == null)

struct node* new=new_node(2); //呼叫函式 新建節點2並返回節點指標new到主函式當中

if(new == null)

//將new node 2插入鍊錶末尾

int ret=tail_ins(head,new);

if( ret == 0)

new =null;

/* 指定位置插入不行(需要先查詢,如果插入失敗),如果插入失敗還讓new=null的話,新節點就找不到了。但是頭插和尾插是可以的*/

//新建資料3的節點並插入末尾

new = new_node(3);

ret=tail_ins(head,new);

if( ret == 0)

new =null;

//鍊錶遍歷

單向鍊錶的尾插

實現乙個單向鍊錶的尾插,首先也是要對原始鍊錶進行判斷,分情況,對於空鍊錶來說,尾插就直接返回node,如果是非空鍊錶,就要通過last找到最後乙個節點,即讓last last.next不斷迴圈,當last.next null時就得到了最後乙個節點,然後讓last.next node,這樣就實現了將n...

尾插法建立鍊錶

include include typedef struct lnode lnode,linklist lnode int tail insert linklist l,int n int tail insert linklist l,int n static lnode l int tailins...

尾插法建立鍊錶

都在注釋裡,emmm include include include using namespace std typedef struct llistllist 尾插法建立單鏈表,r頭指標指向s尾指標 void creatlist llist c,int a,int n r next null 指標...