[LeetCode 第9题] -- Reorder List

简介: 题目链接: Reorder List题目意思: 给的一个链表,要求对链表重新排序。                例如L0->L1->L2....


题目链接: Reorder List

题目意思: 给的一个链表,要求对链表重新排序。

                例如L0->L1->L2.....->Ln,要求重新排序变成L0->Ln-1->L1->Ln-2->L2....

代码:

/**
 * 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);
};

void Solution::reorderList(ListNode *head) {
    if (NULL == head) {
        return;
    }
    int listCount = 0;
    ListNode* tmpHead = head;
    vector<int> listVal;
    while (tmpHead != NULL) {
        listVal.push_back(tmpHead->val);
        tmpHead = tmpHead->next;
        listCount++;
    }
    tmpHead = head;
    int startToEnd = 0;
    int endToStart = listCount-1; 
    while (tmpHead != NULL) {
        tmpHead->val = listVal[startToEnd++];
        tmpHead = tmpHead->next;
        if (tmpHead != NULL) {
            tmpHead->val = listVal[endToStart--];
            tmpHead = tmpHead->next;
        }
    }
}


目录
相关文章
|
9月前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
61 0
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
50 0
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
60 1
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
61 0
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 234. 回文链表 Palindrome Linked List
LeetCode 234. 回文链表 Palindrome Linked List
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 237. 删除链表中的节点 Delete Node in a Linked List
LeetCode 237. 删除链表中的节点 Delete Node in a Linked List
|
7月前
|
Java API Apache
怎么在在 Java 中对List进行分区
本文介绍了如何将列表拆分为给定大小的子列表。尽管标准Java集合API未直接支持此功能,但Guava和Apache Commons Collections提供了相关API。