leetcode每日一题重排链表

it2023-08-22  61

采用一个数组存放每个链表节点指针,就可以对链表节点进行索引了,假设链表长度为,通过分析可以得到:对于链表中第  个结点需要令其后继为第个节点,第个节点的后继为第个节点,代码如下

class Solution { public: void reorderList(ListNode* head) { vector<ListNode*> vec; ListNode* p = head; while (p) { vec.emplace_back(p); p = p->next; } unsigned num = vec.size(); for (unsigned i = 0; i < num / 2; ++i) { vec[i]->next = vec[num - i - 1]; vec[num - i - 1]->next = vec[i + 1]; } if (num > 0) { vec[num / 2]->next = nullptr; } } };

 

最新回复(0)