鍊錶常用操作及面試題

2021-07-02 06:07:56 字數 1642 閱讀 3164

鍊錶是一種比較基礎的資料結構,雖然在acm比賽中不常用,但是在面試中還是比較常問的,所以拿出來寫了一下,發現很多錯誤,由於操作中用到很多指標,所以不經常寫的話很容易寫錯。

這裡寫了一下鍊錶的建立,比較基礎!

然後是刪除鍊錶的元素,需要考慮刪除的是否為第乙個元素。

然後是找鍊錶的倒數第k個元素,可以用兩個指標,乙個指標後移k次,然後兩個同時向後走,當先走k次的走到尾部的時候,另乙個剛好到倒數第k個元素,因為兩個指標的位置一直是相差k的。

最後是反轉鍊錶,邊向後走,邊把鍊錶的指標指向前面的元素就可以了。

notice:

1:鍊錶只有在建立和刪除節點的時候需要分配記憶體,即操作記憶體的時候需要,這是因為鍊錶分配記憶體塊不是連續的,是離散的,即乙個節點乙個節點的分配,所以需要呼叫記憶體分配函式,記憶體分配函式常用的有兩個

c++中的new和c語言中的malloc這個也是面試常問的,即其區別。

呼叫方法的話很簡單,

listnode *node = new listnode();

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

當然別忘了釋放記憶體,其對應的delete和free,寫法如下

delete node;

free(node);

它們兩個有什麼區別呢?

1:now返回指定型別的指標,其可以自動計算所要分配記憶體的大小。而malloc需要強制轉換成實際的型別,並且大小要我們給出來。

2:malloc只管分配記憶體,不對其值進行初始化,即值為隨機的,而new可以初始化

一些練習**:

#include

#include

#include

using namespace std;

struct listnode

;listnode* creat(int n) //建立鍊錶

return head;

}void print(listnode *head) ///列印鍊錶

puts("");

}listnode* removenode(listnode *head,int num)

listnode *tmp =

null;

tmp = head; //記錄找到節點的前乙個節點

while(newhead!=

null) //其他節點

tmp = newhead;

newhead = newhead->next;

}}void find_kthnode(listnode *head,int k) ///查詢倒數第k個元素

while(one!=

null)

printf("find last %dth secessful\n");

printf("%d\n",two->val);

}listnode* reverselist(listnode *head)

return head;

}int main()

return0;}

/*****

101 2 3 4 5 6 7 8 9 10103

******/

鍊錶基本操作及面試題

標頭檔案 ifndef linked list h define linked list h include using namespace std include typedef int datatype struct node datatype data node prev node next ...

鍊錶操作面試題

include using namespace std struct node int value node next node find node phead,int t 一 刪除鍊錶中某個節點 思路 先找到要刪除的節點位置 bool deletet node phead,int t else e...

鍊錶操作面試題

include include include define datetype int typedef struct node node,pnode void printlist pnode head 列印鍊錶 printf null n void bubblesort pnode phead 使用...