利用递归来解决该问题,一层一层处理
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(!head || !head->next) return;
auto temp = head;
int cnt = 0;
while(temp)
{
temp = temp->next;
cnt++;
}
dfs(head, cnt);
}
void dfs(ListNode* head, int len)
{
if(len == 1)
{
head->next = NULL;
return;
}
if(len ==2)
{
head ->next->next = NULL;
return;
}
auto temp = head;
int cnt = len;
while(--cnt)
{
temp = temp -> next;
}
auto temp2 = head->next;
head->next = temp;
temp ->next = temp2;
dfs(temp2, len-2);
}
};