反转部分单向链表

来源:互联网 发布:蝴蝶效应3 知乎 编辑:程序博客网 时间:2024/05/29 06:49

反转部分单向链表:


//反转部分单向链表的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); }}


原创粉丝点击