在刷盼:恚客網(wǎng)試題的時(shí)候發(fā)現(xiàn)和leetcode不一樣的地方辜限,leetcode只需要寫核心算法严蓖,而牛客網(wǎng)需要寫完整程序毫深。對(duì)于鏈表這種題目當(dāng)然避免不了要?jiǎng)?chuàng)建鏈表毒姨,那么就寫下來(lái)鏈表的創(chuàng)建:
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
} ;
ListNode* CreateList(const vector<int> &vec) {
if (vec.empty()) {
return nullptr;
}
auto head = new ListNode(vec.at(0));
ListNode* p = head;
for (size_t i = 1; i < vec.size(); i++) {
auto q = new ListNode(vec.at(i));
p->next = q;
p = p->next;
}
return head;
}
int main(int argc, char **argv) {
vector<int> vec;
vec.push_back(6);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.shrink_to_fit();
ListNode* head = CreateList(vec);
while (head != nullptr) {
cout << head->val << endl;
head = head->next;
}
return 0;
}