投递渠道:boss
timeline:
#include <iostream>
/*
*
* 给定单链表的头节点head,请反转链表,并返回反转后的链表的头节点。
示例 1:输入:head = [1,2,3,4,5]输出:[5,4,3,2,1]
不限定语言和IDE
*
*/
struct Node {
int val_;
Node* next_ = nullptr;
Node(int val) : val_{val} {}
};
Node* reverseList(Node* head) {
Node* prev = nullptr;
Node* cur = head;
while(cur) {
auto next = cur->next_;
cur->next_ = prev;
prev = cur;
cur = next;
}
return prev;
}
void print(Node* head) {
while(head) {
std::cout << head->val_ << ' ';
head = head->next_;
}
std::cout << '\n';
}
void destroy(Node* head) {
while(head) {
auto next = head->next_;
delete head;
head = next;
}
}
void test() {
// [1,2,3,4,5]
auto head = new Node(1);
auto tail = head;
for(int i = 2; i <= 5; i++) {
tail->next_ = new Node(i);
tail = tail->next_;
}
print(head);
head = reverseList(head);
print(head);
destroy(head);
}
int main() {
test();
}
当天晚上 oc,第二天发 offer,已拒