struct Node { int value = 0; Node* next = nullptr; Node(int value_) : value(value_) {} }; Node* createLinkList(const std::vector<int>& data) { if (data.empty()) { return nullptr; } auto head = new Node(data.front()); Node* tail = head; std::for_each(data.cbegin() + 1, data.cend(), [&](int value) { tail->next = new Node(value); tail = tail->next; }); return head; } void printLinkList(Node* head) { while (head) { std::printf("%d ", head->value); head = head->next; } } void destroyLinkList(Node* head) { if (head == nullptr) { return; } if (head->next) { destroyLinkList(head->next); } delete head; } Node* reverseLinkList(Node* old_head) { Node* new_head = nullptr; while (old_head) { Node* next = old_head->next; old_head->next = new_head; new_head = old_head; old_head = next; } return new_head; } Node* removeDuplicates(Node* head) { if (head == nullptr){ return head; } for (auto it = head; it->next;){ if (it->value == it->next->value){ Node* next = it->next->next; delete it->next; it->next = next; }else{ it = it->next; } } return head; } void moveHead(Node** dest_ref, Node** source_ref) { auto new_head = *source_ref; *source_ref = new_head->next; new_head->next = *dest_ref; *dest_ref = new_head; } void sortedInsert(Node** head_ref, Node* new_node) { Node** current_ref = head_ref; while ((*current_ref != nullptr) && (*current_ref)->value < new_node->value){ current_ref = &((*current_ref)->next); } new_node->next = *current_ref; // 前一个结点保存的地址和当前结点的二级指针的解引用是同一个, // 都是 *current_node *current_ref = new_node; } void insertSort(Node** head_ref) { Node* new_head = nullptr; // 如果 for 的第三段使用 it = it->next,是不是一样呢? // 当然不是,因为此时的 it 已经被移动了,所以此时的 it 是在新的链表中, // it->next 得到的是新链表中的 next Node. // 所以要在 it 移动之前保留一份移动前的 next. for(Node* it = *head_ref, *next; it; it = next){ next = it->next; sortedInsert (&new_head, it); } *head_ref = new_head; }
时间: 2024-11-10 20:49:13