1.給定乙個鍊錶,每個節點包含乙個額外增加的隨機指標,該指標可以指向鍊錶中的任何節點或空節點。要求返回這個鍊錶的深拷貝。
解:為了實現在o(n)的時間複雜度內完成操作,可以先複製每乙個結點到其後面,在複製其random指標,最後進行拆分
1.複製每乙個結點,並接在原始結點的後面
2.根據原始結點複製random指標。
3.刪除奇數字置的結點,連線偶數字置的結點。
//複製random指標
//原始結點a的random指向c,則a'指向c'
current = head;
while (current)
current = p_newnode->next;//更新當前指標
} //奇數字置是原鍊錶,偶數字置是複製後的鍊錶,拆分即可
current = head;
node* even_head_node = null;
node* even_node = head;
if (current)
while (current)
return even_head_node;
}};int main()
2.給定乙個鍊錶,判斷鍊錶中是否有環。為了表示給定鍊錶中的環,我們使用整數pos
來表示鍊錶尾連線到鍊錶中的位置(索引從 0 開始)。 如果pos
是-1
,則在該鍊錶中沒有環。
輸入:head = [3,2,0,-4], pos = 1輸出:true解釋:鍊錶中有乙個環,其尾部連線到第二個節點。
**:
3.在 o(n log n) 時間複雜度和常數級空間複雜度下,對鍊錶進行排序。#include using namespace std;
struct listnode
};class solution
return 0;
}};int main()
示例 1:輸入:4->2->1->3輸出:1->2->3->4
解:採用歸併排序,通過設定兩個指標,找到鍊錶的一半
**:
4.編寫乙個程式,找到兩個單鏈表相交的起始節點。#include using namespace std;
struct listnode
};class solution
listnode* mergesortlist(listnode* head)
pre->next = null;
listnode* l = mergesortlist(head);
listnode* r = mergesortlist(slow);
return mergelist(l, r);
} listnode* mergelist(listnode*l, listnode* r)
else
}};int main()
while (h1 && (h2))//此時兩個鍊錶的長度一樣
return null;
}};int main()
5.反轉乙個單鏈表。
示例:輸入:1->2->3->4->5->null輸出:5->4->3->2->1->null
6.請判斷乙個鍊錶是否為回文鍊錶。#include using namespace std;
struct listnode
};class solution
return reverse_head;
}};int main()
示例 1:輸入:1->2->2->1輸出:true
解:判斷回文鍊錶,即判斷首尾元素是否相等,,首元素可以利用鍊錶移動尾元素可以利用棧來進行彈出。
**:
8.給定乙個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。請嘗試使用原地演算法完成。你的演算法的空間複雜度應為 o(1),時間複雜度應為 o(nodes),nodes 為節點總數。#include #includeusing namespace std;
struct listnode
};class solution
current = head;
for (int i = 0; i < len/2; i++)
s.pop();
current = current->next;
} return 1;
}};int main()
};class solution
};int main()
輸入:2->1->3->5->6->4->7->null
輸出:2->3->6->7->1->5->4->null
解:偶節點始終在奇節點後面,因此定義兩個指標分別指向偶節點和奇節點,進行間隔指向。
**:
using namespace std;
struct listnode
};class solution
odd->next = evenhead;
return head;
}};int main()
4 力扣2023年常見程式設計題總結 堆 棧和佇列
1.設計乙個支援 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。解 前四個操作均可以使用stack來完成,檢索最小元素,需要重新用乙個新的stack來儲存每次壓入元素的最小值。using namespace std class minstack void push int x ...
力扣程式設計題
1.給定乙個整數陣列 nums 和乙個整數目標值 target,在該陣列中找出 和為目標值 的那 兩個 整數,並返回它們的陣列下標。你可以假設每種輸入只會對應乙個答案。但是,陣列中同乙個元素不能使用兩遍。你可以按任意順序返回答案。列舉陣列中的每乙個數 x,尋找陣列中是否存在 target x。2.數...
力扣程式設計題05
面試題05.替換空格 請實現乙個函式,把字串 s 中的每個空格替換成 20 示例 1 限制 0 s 的長度 10000 class solution 1221.分割平衡字串 在乙個 平衡字串 中,l 和 r 字元的數量是相同的。給出乙個平衡字串 s,請你將它分割成盡可能多的平衡字串。返回可以通過分割...