码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(92):Reverse Linked List II

时间:2016-01-18 20:35:23      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

LeetCode(92):Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/Lewisr/p/5140214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!