链表混插L: L 0→L 1→…→L n-1→L n,reorder it to: L 0→L n →L 1→L n-1→L 2→L n-2→…

时间:2021-03-25 22:36:16

题目:

Given a singly linked list LL 0L 1→…→L n-1L n,
reorder it to: L 0L n L 1L n-1L 2L n-2→…

You must do this in-place without altering the nodes' values.

For example,

Given{1,2,3,4}, reorder it to{1,4,2,3}.

首先用一个vector存储所有的结点,然后将倒数第i个结点插入到第i个结点之后。

实现:


 * 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) {

       ListNode *p = head;
       vector<ListNode*> nodes;   //用于存储结点;
       if (head == NULL)
        {
            return;
        }
        while (p)             //将链表中所有结点存储在node中;
        {
            nodes.push_back(p);      //存储的是结点,而不是结点指向的值;
            p = p->next;
        }
        int left = 0;
        int right = nodes.size() - 1;
        while (left < right)                 //头尾方向的指针移动;
        {
            nodes[left]->next = nodes[right];
            nodes[right--]->next = nodes[++left];
        }
        nodes[left]->next = NULL;        //令最后一个结点的指针域为空;
    }
};