leetcode——92. 反转链表 II

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        a=ListNode(0)
        a.next=head
        q=a
        p=head
        s=1
        stack=[]
        while s<m:
            p=p.next
            q=q.next
            s+=1
        while s>=m:
            stack.append(p)
            p=p.next
            s+=1
            if s==n+1:break
        while stack:
            q.next=stack.pop()
            q=q.next
执行用时 :20 ms, 在所有 python 提交中击败了80.59%的用户
内存消耗 :12 MB, 在所有 python 提交中击败了16.05%的用户
 
——2019.11.01
 

public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev_m = dummy,prev = dummy;
        for(int i = 1;i<=n;i++){
            if(i == m){
                prev_m = prev;
            }
            if(i > m && i <= n){
                prev.next = head.next;
                head.next = prev_m.next;
                prev_m.next = head;
                head = prev;
            }
            prev = head;
            head = head.next;
        }
        return dummy.next;
    }

 

 

——2020.7.13

posted @ 2019-11-01 15:12  欣姐姐  阅读(111)  评论(0编辑  收藏  举报