首页 > 其他分享 >Leetcode 重排链表 递归

Leetcode 重排链表 递归

时间:2023-01-05 11:00:30浏览次数:50  
标签:head xi 递归 next 链表 tail 重排 Leetcode

https://leetcode.com/problems/reorder-list/solutions/45113/Share-a-consise-recursive-solution-in-C++/

https://leetcode.cn/problems/reorder-list/solutions/32910/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-34/

列表的核心就是随机访问,无法得到任意位置的节点

1->2->3->...->n-2->n-1->n->#

1->n->2->n-1->3->...->(odd: (n+1)/2,even: n/2->n/2+1)->#

比如

  • 1->2->3->4->5->6->#
  • 1->6->f(2->3->4->5->#)

注意不是 1->f(2->3->4->5->6->#)

  • 1->6->2->5->f(3->4->#)
  • 1->6->2->5->3->4>#

因此这里存在子结构

但是递归基怎么写呢

  • 1->6->f(2->3->4->5->#)
  • 1->6->f(2->3->4->5->#) = 1->g(1->next) = 1->g(6->2->5->3->4>#)

我们只有一个head,比如说1

f(1) = 1->g(1->next) = 1->g(2) = 1->6->f(2)

f(head) = head->g(head->next)
g(head) = tail(head)->f(head->next)
f(head) = head->tail(head->next)->f(head->next->next)

问题在于此!tail无法实现

标签:head,xi,递归,next,链表,tail,重排,Leetcode
From: https://www.cnblogs.com/zxyfrank/p/17026554.html

相关文章

  • 【栈】LeetCode 1209. 删除字符串中的所有相邻重复项 II
    题目链接1209.删除字符串中的所有相邻重复项II思路用栈存储Pair<Character,Integer>,整数表示该字符连续出现的次数。遍历字符串s将其中的字符c依次压入栈顶并......
  • 【栈】LeetCode 1472. 设计浏览器历史记录
    题目链接1472.设计浏览器历史记录思路用栈history模拟网页的前进后退操作,用栈temp来暂时存储后退所退出的网页。代码classBrowserHistory{Stack<String>h......
  • [LeetCode] 2453. Destroy Sequential Targets
    Youaregivena 0-indexed array nums consistingofpositiveintegers,representingtargetsonanumberline.Youarealsogivenaninteger space.Youhave......
  • leetcode-653. 两数之和 IV - 输入二叉搜索树
    653.两数之和IV-输入二叉搜索树-力扣(Leetcode)用了迭代进行遍历二叉树,因为二叉搜索树的中序遍历是有序的,所以肯定左边大于右边,然后就可以用一个map来存放之前的数值,......
  • [LeetCode]015-三数之和
    >>>传送门题目给你一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]]满足i!=j、i!=k且j!=k,同时还满足nums[i]+nums[j]+nums[k]==0......
  • leetcode-387-easy
    FirstUniqueCharacterinaStringGivenastrings,findthefirstnon-repeatingcharacterinitandreturnitsindex.Ifitdoesnotexist,return-1.Examp......
  • leetcode-414-easy
    ThirdMaximumNumberGivenanintegerarraynums,returnthethirddistinctmaximumnumberinthisarray.Ifthethirdmaximumdoesnotexist,returnthemaxim......
  • leetcode-563-easy
    BinaryTreeTiltGiventherootofabinarytree,returnthesumofeverytreenode'stilt.Thetiltofatreenodeistheabsolutedifferencebetweenthesum......
  • leetcode-349-easy
    IntersectionofTwoArraysGiventwointegerarraysnums1andnums2,returnanarrayoftheirintersection.Eachelementintheresultmustbeuniqueandyoum......
  • leetcode-350-easy
    IntersectionofTwoArraysIIGiventwointegerarraysnums1andnums2,returnanarrayoftheirintersection.Eachelementintheresultmustappearasmany......