一些简单的链表算法一
??? 鏈表是很重要的一種數(shù)據(jù)結(jié)構(gòu),又是一種看似簡單但很難熟練掌握的東西,究其主要原因應(yīng)該就是它與指針結(jié)合的太緊密了。為了讓大家更好的學(xué)習(xí),特將一些簡單的算法羅列如下,大家一起探討(用c寫的而且是不帶頭結(jié)點(diǎn)的)
首先是鏈表的結(jié)構(gòu)體:
typedef struct node
{
??? int data;
?struct node* next;
}LIST;
1、往鏈表中壓入元素
void Push(LIST **headRef,int newData) {LIST *newNode = new(LIST);newNode->data = newData;newNode->next = *headRef;*headRef = newNode; }如果我們加入的順序是1、2、3則得到的鏈表是{3、2、1}
我們簡單構(gòu)建一個(gè)鏈表{1、2、3}:
LIST* BuildOneTwoThree() {LIST *head = 0;Push(&head,3);Push(&head,2);Push(&head,1);return head; }2、計(jì)算鏈表的長度
int Length(LIST*head) {LIST *current = head;int length = 0;while(current != 0){length++;current = current->next;}return length; }3、計(jì)算給定一個(gè)元素計(jì)算在鏈表中出現(xiàn)的次數(shù)
int Count(LIST*head,int data_to_find) {int count = 0;LIST *current = head;while(current != 0){if(current->data == data_to_find)count++;current = current->next;}return count; }4、 給定一個(gè)索引取出那個(gè)位置的值(索引是從0開始的)
int GetNth(LIST*head,int index) {LIST *current = head;assert(head != 0);assert(index >= 0);for(index; index > 0; index--){current = current->next;}return current->data; }5、刪除一個(gè)鏈表并釋放所有內(nèi)存將頭指針指向NULL
void DeleteList(LIST**headRef) {LIST*current = *headRef;LIST*next = 0;for(current ; current != 0;){next = current->next;delete(current);current = next;}*headRef = 0; }6、彈出第一個(gè)元素并刪除第一個(gè)節(jié)點(diǎn)
int Pop(LIST**headRef) {int data = 0;assert(*headRef != 0);LIST *current = *headRef;data = (*headRef)->data;*headRef = (*headRef)->next;delete(current);return data;}7、在給定索引處插入元素
void InsertNth(LIST**headRef,int index,int newData) {if(index == 0){Push(headRef,newData);}else{LIST*current = *headRef;for(index; index > 1; index--){assert(current != NULL);current = current->next;}assert(current != 0);Push(¤t->next,newData);} }上面的都是一些關(guān)于鏈表簡單的算法,有些是參考斯坦福大學(xué)的講義而來的,特此說明
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/self-control/archive/2012/12/27/2835347.html
總結(jié)
以上是生活随笔為你收集整理的一些简单的链表算法一的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。