zoukankan      html  css  js  c++  java
  • LeetCode(92):Reverse Linked List II

    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 ≤ mn ≤ length of list.

    题意:反转链表,反转指定位置的链表。

    思路:参考这里,主要是先找到要反转链表的开始反转的结点,然后一个个的反转,最后和其两边的部分进行连接。

    代码:

    public ListNode reverseBetween(ListNode head, int m, int n) {
             if(head==null) return null;
             ListNode q = null;
             ListNode p = head;
             for(int i=0;i<m-1;i++){
                 q = p;
                 p = p.next;
             }
             ListNode end = p;
             ListNode pPre = p;
             p = p.next;
             for(int i=m+1;i<=n;i++){
                 ListNode pNext = p.next;
                 p.next = pPre;
                 pPre = p;
                 p = pNext;
             }
             end.next = p;
             if(q!=null)
                q.next = pPre;
            else
                head = pPre;
            return head;
        }
  • 相关阅读:
    基于Spring的集群会话共享方案-spring session
    Tensorflow 模型线上部署
    Dijkstra算法
    BFS和DFS
    图的基本概念
    排序5
    排序4
    排序3
    排序2
    排序1
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5140214.html
Copyright © 2011-2022 走看看