• LeetCode OJ


    题目:

      Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-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}.

    解题思路:

      1、用快慢指针找到链表的中点,并将链表分割成两部分

      2、翻转后面的部分

      3、将前后两部分拼接

    /**
     * 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 == NULL) return;
    
            //find the last part
            ListNode *mid = head, *last = head;
            while (last != NULL) {
                last = last->next;
                if (last == NULL) break;
                last = last->next;
    
                mid = mid->next;
            }
            ListNode *right_head = mid->next;
            mid->next = NULL;
    
            //翻转 右边部分
            ListNode *pre = NULL, *suf = right_head;
            while (suf != NULL) {
                ListNode * tmp = suf->next;
                if (tmp == NULL) {
                    right_head = suf;
                }
                suf->next = pre;
                pre = suf;
                suf = tmp;
            }
    
            //拼接
            ListNode *cur = head;
            while (cur != NULL && right_head != NULL) {
                ListNode *tmp = right_head->next;
                right_head->next = cur->next;
                cur->next = right_head;
                right_head = tmp;
                cur = cur->next->next;
            }
        }
    };
  • 相关阅读:
    初步理解Java的三大特性——封装、继承和多态
    设计模式
    区分super和this
    类—矩形面积
    生成不重复的随机数(待完善)
    关于类的创建和调用
    生成验证码
    endsWith和startsWith同样效果其他形式的写法(2016.1.12)
    去除字符串中空格的方法(2016.1.12P141-2)
    java的抽象类
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3726345.html
Copyright © 2020-2023  润新知