單鏈表的基本操作

2021-08-09 13:28:03 字數 2841 閱讀 6879

單鏈表的基本操作

1、標頭檔案(list.h)

#pragma once

//帶頭節點的單鏈表,尾節點的next為null

//頭節點起哨兵位作用,它不使用(資料域不能儲存資料)

typedef struct node

node,*list;//list == node*

//typedef struct node *list;

//鍊錶初始化

void initlist(list plist);

//頭插

bool insert_head(list plist,int val);

//尾插

bool insert_tail(list plist,int val);

//查詢

node *search(list plist,int key);

//刪除

bool delete(list plist,int key);

//獲取單鏈表的長度

int getlength(list plist);

//判空

bool isempty(list plist);

//清空

void clear(list plist);

//摧毀

void destroy(list plist);

//列印

void show(list plist);

//獲取元素

bool getelem(list plist,int pos,int *rtval);

//逆置

void reverse(list plist);//考試的重點內容

//除去重複的資料值

void unique(list plist);

2、原始檔

#include#include#include#include"list.h"

//鍊錶初始化

void initlist(list plist)

plist->next = null;

}//頭插 時間複雜度o(1)

bool insert_head(list plist,int val)

node *p = (node *)malloc(sizeof(node));

p->data = val;

p->next = plist->next;

plist->next = p;

return true;

}//尾插

bool insert_tail(list plist,int val)

//查詢

node *search(list plist,int key)

for(node *p = plist->next;p != null;p = p->next) }

return null;

}//刪除

bool delete(list plist,int key)

} return false;

}//獲取單鏈表的長度

int getlength(list plist)

return count;

}//判空

bool isempty(list plist)

//清空

void clear(list plist)

//摧毀

void destroy(list plist)

}//列印

void show(list plist)

printf("\n");

}//獲取元素

bool getelem(list plist,int pos,int *rtval)

int i = 0;

for(node *p = plist->next;p != null;p= p->next)

i++;

} return false;

}//得到結點p的前驅

static node *getpri(list plist,node *p)

} return null;

}//逆置

void reverse(list plist)//考試的重點內容

//時間複雜度為o(n),並且最好,利用了頭插法的思想

node *p = plist->next;

node *q;

plist->next = null;

while(p != null)

/*//時間複雜度為o(n^2)

node *p = plist->next;

node *q;

int tmp;

for(q = plist;q->next != null;q = q->next);

for(int i = 0;i < getlength(plist)/2;i++)

*/}//除去重複的資料值

void unique(list plist)

} }}

3、測試原始檔

#include#include#include"list.h"

int main()

show(&head1);

show(&head2);

reverse(&head1);

show(&head1);

int val;

getelem(&head2,3,&val);

printf("%d\n",val);

destroy(&head1);

destroy(&head1);

return 0;

}

單鏈表基本操作

include include include include includeusing namespace std typedef struct node node,plinklist plinklist createfromhead node pstnode node malloc sizeof...

單鏈表基本操作

單鏈表的初始化,建立,插入,查詢,刪除。author wang yong date 2010.8.19 include include typedef int elemtype 定義結點型別 typedef struct node node,linkedlist 單鏈表的初始化 linkedlist...

單鏈表基本操作

include using namespace std define namelenth 20 define ok 0 define error 1 typedef struct flagnode node 生成結點 inline node newnode 銷毀化煉表 void destroylin...