题解 | #链表内指定区间反转#

链表内指定区间反转

http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

using System.Collections.Generic;

/*
public class ListNode
{
	public int val;
	public ListNode next;
	public ListNode (int x)
	{
		val = x;
	}
}
*/
class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        ListNode m_last_node=null;
        ListNode m_node=null;
        ListNode n_node=null;
        ListNode n_next_node=null;
        int currect=1;
        ListNode temp_node=head;
        while(temp_node!=null){
            if(currect==m-1)
                m_last_node=temp_node;
            if(currect==m)
                m_node=temp_node;
            if(currect==n)
                n_node=temp_node;
            currect++;
            temp_node=temp_node.next;
        }
        if(n_node.next!=null)
            n_next_node=n_node.next;
        if(m_last_node!=null)
            m_last_node.next=null;
        n_node.next=null;
        
        ListNode reverse_head=Reverse(m_node);
        
        if(m_last_node!=null)
            m_last_node.next=reverse_head;
        else
            head=reverse_head;
        ListNode reverse_tail=GetTailNode(reverse_head);
        if(n_next_node!=null)
            reverse_tail.next=n_next_node;
        return head;
    }
    ListNode Reverse(ListNode head){
        ListNode last=null;
        ListNode crr=head;
        ListNode next=null;
        while(crr!=null){
            next=crr.next;
            crr.next=last;
            last=crr;
            crr=next;
        }
        return last;
    }
    ListNode GetTailNode(ListNode head){
        while(head.next!=null)
            head=head.next;
        return head;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务