LEETCODE,LeetCode OJ - Reorder List

 2023-10-18 阅读 30 评论 0

摘要:題目: LEETCODE。  Given a singly linked list?L:?L0→L1→…→Ln-1→Ln,reorder it to:?L0→Ln→L1→Ln-1→L2→Ln-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

題目:

LEETCODE。  Given a singly linked list?L:?L0→L1→…→Ln-1→Ln,
reorder it to:?L0→LnL1→Ln-1→L2→Ln-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 partListNode *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;}}
};

?

轉載于:https://www.cnblogs.com/dongguangqing/p/3726345.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/147686.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息