首页 > 其他 > 详细

leetcode_92_Reverse Linked List II

时间:2015-02-04 21:48:15      阅读:272      评论:0      收藏:0      [点我收藏+]

描述:

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.

思路:

这种题目,举个例子能让思路更加清晰,通过在草纸上演算可知,题目要分两种情况,m==1和m>1的情况,然后就是围绕这两种情况展开讨论,删除后面的结点,然后将后面的结点添加到前面,一次搞定,bravo!

代码:

public ListNode reverseBetween(ListNode head, int m, int n) {
		if (head==null) {
			return null;
		}
        ListNode p =head,q=head,temp=null;
        int i=0;
        for(i=0;i<m-1;i++)
        	q=q.next;
        for(i=0;i<m-2;i++)
        	p=p.next;
        if(m==1)
        {
        	for(i=0;i<n-m;i++)
            {
            	//delete the node in the list
            	temp=q.next;
            	q.next=temp.next;
            	//insert the node in the list
            	temp.next=p;
            	p=temp;
            }
        	head=p;
        }else 
        {
        	for(i=0;i<n-m;i++)
            {
            	//delete the node in the list
            	temp=q.next;
            	q.next=temp.next;
            	//insert the node in the list
            	temp.next=p.next;
            	p.next=temp;
            }
		}
		return head;
    }


结果:

技术分享

leetcode_92_Reverse Linked List II

原文:http://blog.csdn.net/mnmlist/article/details/43493399

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!