zoukankan      html  css  js  c++  java
  • 反转部分单向链表

    题目描述:

      给定一个单向链表的头节点head,以及两个整数from和to,在单向链表上把第from个节点到第to个节点这一部分进行反转。

      例如:

      1-->2-->3-->4-->5-->6-->null,from=3,to=5

      调整结果为:1-->2-->5-->4-->3-->6-->null

      1-->2-->3-->null,from=1,to=3

      调整结果为:3-->2-->1-->null

    要求:

      1、如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)。

      2、如果不满足1<=from<=to<=N,则不用调整。

    题目分析及解题思路:

      在对部分链表进行反转时,1-->2-->3-->4-->5-->null,from=2,to=4。我们要知道from-1的节点fPre,以及to+1处的节点tPos,这样,部分链表反转过程如下:

      fPre此时指向链表中的1,pre = fPre.next,将1节点的下一个节点赋为pre,pre的下一个节点赋为cur,那么此时链表的部分反转就和整条链表的反转过程相同,唯一不同的是将pre = tPos。

      问题解决的办法首先是要找到from的前一个节点和to的下一个节点。然后对from到to处的节点进行反转。最后还要判断的是:如果fPre = None的话,返回新链表的头节点即可,否则返回原来的头节点。

    代码实现:

     1 def reversePart(head, frm, to):
     2     cur = head
     3     fPre = None
     4     tPos = None
     5     length = 0
     6     while cur:
     7         length += 1
     8         if length == frm - 1:
     9             fPre = cur
    10         else:
    11             fPre = fPre
    12         if length == to + 1:
    13             tPos = cur
    14         else:
    15             tPos = tPos
    16         cur = cur.next
    17     if frm > to or frm < 1 or to > length:
    18         return head
    19     if fPre:
    20         pre = fPre.next
    21     else:
    22         pre = head
    23     cur = pre.next
    24     pre.next = tPos
    25     while cur != tPos:
    26         next_ = cur.next
    27         cur.next = pre
    28         pre = cur
    29         cur = next_
    30     if fPre:
    31         fPre.next = pre
    32         return head
    33     return pre
    View Code
  • 相关阅读:
    hihocoder 1049 后序遍历
    hihocoder 1310 岛屿
    Leetcode 63. Unique Paths II
    Leetcode 62. Unique Paths
    Leetcode 70. Climbing Stairs
    poj 3544 Journey with Pigs
    Leetcode 338. Counting Bits
    Leetcode 136. Single Number
    Leetcode 342. Power of Four
    Leetcode 299. Bulls and Cows
  • 原文地址:https://www.cnblogs.com/dabric/p/11723126.html
Copyright © 2011-2022 走看看