leetcode之重排链表

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

简要题解:

定义一个vector然后把链表插入后直接根据vector操作即可简要代码如下:

/**
 * 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)return;
         vector<ListNode*>ve;
         ListNode* cur=head;
         while(cur)
         {
             ve.push_back(cur);
             cur=cur->next;
         }
         int l=0,r=ve.size()-1;
        while(l<r)
        {
            ve[l]->next=ve[r];
            ve[r--]->next=ve[++l];
        }
        ve[l]->next=NULL;
    }
};
发布了49 篇原创文章 · 获赞 2 · 访问量 3525

猜你喜欢

转载自blog.csdn.net/qq_40623603/article/details/105652281