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

Leetcode#79Word Search

时间:2015-05-17 18:53:58      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:following   position   example   public   linked   

Reverse Linked List II

 Total Accepted: 39279 Total Submissions: 150148My Submissions

Question Solution 


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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

分析,顺序扫描链表,找出需要旋转的片段,旋转,关键点测试样例,全局旋转和部分旋转

public class Solution {

    public ListNode reverseBetween(ListNode head, int m, int n) {

        

        if(head==null)

            return head;

        else if(head.next==null)

            return head;

        else if(m<1)

            m=1;

        else if(m>=n)

            return head;

        

        ListNode x=new ListNode(0);

        x.next=head;

        ListNode y=x;

        int i=1;

        

        while(i<m)

        {

            y=y.next;

            i++;

        }

        

        if(y.next==null)

            return head;

        else

        {

            int j=0;

            ListNode e=y.next;

            ListNode z=y.next;

            ListNode v=z.next;

            while(j<n-m+1&&v!=null)

            {

                z.next=y.next;

                y.next=z;

                z=v;

                v=z.next;

                j++;

            }

            if(j==n-m+1)

                e.next=z;

            else

            {

                z.next=y.next;

                y.next=z;

                e.next=v;

            }

            return x.next;

        }

        

    }

}


Leetcode#79Word Search

标签:following   position   example   public   linked   

原文地址:http://7061299.blog.51cto.com/7051299/1652080

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