标签:
https://leetcode.com/problems/reverse-linked-list-ii/
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
题目:将指定位置段的结点逆序。(借鉴了Reverse Nodes in k-Group 的reverse 函数的逆序方法)
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @param {ListNode} head 9 # @param {integer} m 10 # @param {integer} n 11 # @return {ListNode} 12 def reverseBetween(self, head, m, n): 13 if head==None or head.next==None: 14 return head 15 dummy=ListNode(0) 16 dummy.next=head 17 head1=dummy 18 for i in range(m-1): 19 head1=head1.next #head1放在起始m的前一项 20 p=head1.next #p放在起始项m处 21 for i in range(n-m): #循环n-m次以下操作,将1号项的所有后面项依次前置,导致逆序 22 tmp=p.next; p.next=tmp.next #将第2项去掉,保持后面连接 23 tmp.next=head1.next; head1.next=tmp #将第2项放在排序列的开头 24 return dummy.next #2,3,4,5--3,2,4,5--4,3,2,5--5,4,3,2,将2后面的数依次前置,需要n-m次此操作
标签:
原文地址:http://www.cnblogs.com/lzsjy421/p/4607253.html