演算法總結——鍊錶:
#include #include#include
using
namespace
std;
struct
listnode;
};//
陣列建立鍊錶
listnode* constructlinkedlist(vectorlist)
p->next=null;
return
head;}//
列印鍊錶
void printlist(listnode*head)
return;}
//插入節點(頭插)
listnode* insertnode(listnode* head,int
val)
//查詢節點
listnode* findnode(listnode* head,int
val)
return
null;}//
刪除節點
listnode* deletenode(listnode* head,int
val)
//delete the head node
listnode* p=head;
if(head->val==val)
listnode* q=p;
while(p!=null)
else
}p=p->next;
q=p;
}return
head;}//
反轉鍊錶
listnode* reverselist(listnode*head)
p->next=q;
head->next=null;
returnp;}
//找出單鏈表的倒數第k個元素
listnode* findthenode(listnode* head,int
k)
if(k<0
)
return
p;
while(p!=null)
returnq;}
//兩個單鏈表相交,計算相交點
//解法1:對齊長度後再迴圈判斷
//解法2:鍊錶a的尾巴指向鍊錶b的頭部,判斷環入口點
listnode* findinsectnode(listnode* l1,listnode*l2)
returnq;}
//找出中間節點
listnode* findmiddlenode(listnode*head)
returnq;}
//單鏈表氣泡排序,時間複雜度o(n2)
listnode* sortlist1(listnode*head)
while(length>0
) }}//
單鏈表插入排序
listnode* insertionsortlist(listnode*head)
if(s2!=p)
else
}return newhead->next;
}//單鏈表排序,時間複雜度o(nlogn)——歸併排序,詳見leetcode sort list
//合併兩個有序鍊錶,虛擬節點法——詳見歸併排序的merge
//判斷鍊錶是否有環
bool hascycle(listnode *head)
if(quick==null||quick->next==null)
return
false
;return
true;}
//判斷鍊錶是否有環,如果有環,計算環的長度;如果無環,則返回-1
bool calcircle(listnode* head,listnode* intersect,int&cirlen)
if(head->next->next==head)
listnode* quick=head->next->next,*slow=head;
while((quick!=null&&quick->next!=null)||slow!=quick)
if(quick==null||quick->next==null)
return
false
;
if(slow==quick)
return
true;}
//刪除單鏈表中重複的元素,借助map實現
listnode* deletecopy(listnode*head)
else
}return
head;}//
用鍊錶模仿大整數加法,leetcode有類似題目,當時用的是迴圈,此次試試遞迴
listnode* addnumber(listnode* l1,listnode* l2,int&carry)
listnode* tmp=l1;
if(l1==null||l2==null)
else
return
tmp;
}carry+=(l1->val+l2->val);
tmp->val=carry%10
; carry/=10
; tmp->next=addnumber(l1->next,l2->next,carry);
return
tmp;
}struct
listoflist;
//二級鍊錶,每個節點指向乙個鍊錶,將其轉為單鏈表
listnode* generatelist(listoflist*hlist)
return
ret;
}
常考演算法 鍊錶總結
面試 考試速查 常考資料結構型別速查速補表 單鏈表 雙向鍊錶 約瑟夫環 棧 棧實現計算器 字首,中綴,字尾表示式,逆波蘭計算器的實現 遞迴,迷宮回溯,八皇后 排序演算法基礎 氣泡排序 選擇排序 插入排序 希爾排序 快速排序 歸併排序 基數排序 各種排序的比較 二叉排序樹 bst刪除一棵子樹的節點 二...
棧佇列鍊錶演算法總結
1.佇列 struct queue 2.棧棧的基本操作 定義棧 stacks 入棧 定義棧元素 s.push i 出棧 刪除棧元素 s.pop 返回棧頂元素的值 s.top 判斷棧是否為空 s.empty 值為0說明不空 值為1說明棧為空 棧的用法例項 include include using n...
演算法 鍊錶 鍊錶分隔(鍊錶劃分)
給定乙個鍊錶和乙個特定值 x,對鍊錶進行分隔,使得所有小於 x 的節點都在大於或等於 x 的節點之前。你應當保留兩個分割槽中每個節點的初始相對位置。示例 輸入 head 1 4 3 2 5 2,x 3 輸出 1 2 2 4 3 5 兩個臨時頭結點和尾節點,組成兩個鍊錶,分別存放較小和較大節點 完成後...