反转部分单向链表

反转部分单向链表:


//反转部分单向链表的
public class ReverseSubList{
     
     //链表节点的定义
    public static class Node{

    	public int value;
    	public Node next;
         
        //节点的定义
    	public Node(int data)
    	{

    		 this.value=data;
    	}
    }   
     

    //反转部分链表
   public static Node reverseSublist(Node head, int from,int to)
    {

    	if(head==null||from <0||to<0)
    	{
    		return head;
    	}
        Node p=head;
    	int leng=0;
    	Node tPre=null; //获取反转起始节点的前一个节点
        Node tPos=null; //获取反转结束节点的后一个节点
    	//计算链表长度
    	while(p!=null)
     	{
           ++leng;
           tPre=(leng==from-1?p:tPre); //找到反转起始节点的前一个节点
           tPos=(leng==to+1?p:tPos);    //找到反转结束节点的后一个节点
           p=p.next;
    	}
    	if(from>leng||to>leng||from>to)
    	{
    		return head;
    	}
    	p=tPre==null?head:tPre.next;  //找到要起始反转的节点
    	Node node2=p.next;    
        p.next=tPos;  //起始反转的节点指向反转结束节点的后一个节点
         
        Node next=null;
        while(node2!=tPos)
        {
        	next=node2.next;
        	node2.next=p;
        	p=node2;
        	node2=next;
        }
        if(tPre!=null)
        {
        	tPre.next=p;
        	return head;
        }

        return p;
      
     
    }

    //打印链表
    public static void PrintList(Node head)
    {
    	while(head!=null)
    	{

    		System.out.print(head.value+" ");
    		head=head.next;
    	}

    	System.out.println();

    }
	public static void main(String []args)
	{

		Node node=new Node(1);
		node.next=new Node(2);
		node.next.next=new Node(3);
		node.next.next.next=new Node(4);
		node.next.next.next.next=new Node(5);

		PrintList(node);
		Node mode=reverseSublist(node,2,4); //反转节点2---4
        PrintList(mode);
 

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值