Reversed part way linked list

Subject description:

  Given a singly linked list of nodes head head, and two integers from and to, on the way from the list of the node to the second node to the inverting portion.

  E.g:

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

  Adjustment result is: 1 -> 2 -> 5 -> 4 -> 3 -> 6 -> null

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

  Adjustment result is: 3 -> 2 -> 1 -> null

Claim:

  1, if the chain length is N, the time complexity requirements of O (N), additional space requirements complexity O (1).

  2, if 1 <= from not satisfied <= to <= N, then no adjustment.

Topic analysis and problem-solving ideas:

  When partial list of inverting, 1 -> 2 -> 3 -> 4 -> 5 -> null, from = 2, to = 4. We know from-1 fPre node, and a node to + tPos at 1, so that part of the list reversing process is as follows:

  At this point the list of fPre 1, pre = fPre.next, the next node is assigned a node pre, pre next node is assigned cur, then the time reversed portion of the list on the list and the whole trans turn the same procedure, the only difference is the pre = tPos.

  Problem-solving approach is to first find the next node to the previous node and from the. Then from the node to be reversed at. Finally, the judgment is: if fPre = None, then return to the first node to the new list, or else return to the original head node.

Code:

 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

Guess you like

Origin www.cnblogs.com/dabric/p/11723126.html