LeetCode 143.Reordered List

来源:互联网 发布:霓虹灯动画软件 编辑:程序博客网 时间:2024/04/28 09:57

题目链接:https://leetcode.com/problems/reorder-list/

题目描述:

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}.

Subscribe to see which companies asked this question

思路:先将链表分为前后部分,后一部分逆序(设置快慢指针),再将两个链表连接起来

class Solution {public:ListNode* reorderList(ListNode* head) {if (head == NULL || head->next == NULL || head->next->next == NULL)return head;ListNode *pre = NULL, *res = head, *p = head, *q = head, *tmp1 = head, *tmp2 = head;int len = 1;//链表长度计数int count = 0;//划分前后子链表的时候计数//获取链表的长度lenwhile (p->next != NULL){len++;p = p->next;}p = head;//将链表分为两部分,后一个子链表倒序while (q!= NULL){//判断是否到了后一部分if (count>(len - 1) / 2 && count<len){q = p->next;p->next = pre;pre = p;p = q;}else{q = p->next;//前一部分末尾的next置空节点if (count == (len - 1) / 2)p->next = NULL;p = q;}count++;}//此时pre指向逆序子链表的表头,tmp2为其慢指针,tmp1为前半部分子链表的慢指针while (tmp2 != NULL){tmp1 = head->next;tmp2 = pre->next;head->next = pre;pre->next = tmp1;head = tmp1;pre = tmp2;}return res;}};

参考链表逆序的文章:http://blog.csdn.net/autumn20080101/article/details/7607148

0 0