反转链表(Java)

class  Node{
     
    int data;
    Node next;
    public  Node (){
     

    }
    public Node(int data) {
     
        this.data = data;

    }
    public  Node(int data,Node next){
     
        this.data = data;
        this.next = next;
}

}


public class 反转链表II {
     
//创建链表
    public  static  Node createNode (){
     
        Node n1=new Node (1);
        Node n2=new Node (2);
        Node n3=new Node (3);
        Node n4=new Node (4);
        Node n5=new Node (5);
        Node n6=new Node (6);
        n1.next=n2;
        n2.next=n3;
        n3.next=n4;
        n4.next=n5;
        n5.next=n6;
        n6.next=null;
        return  n1;
    }
    public  static  void print(Node h){
     
        while(h!=null){
     
           System.out.print(h.data+" ");
           h=h.next;
        }
        System.out.println();
    }

    //反转链表 头插法
/*
* 在遍历链表时,将当前节点的 next 指针改为指向前一个节点。由于节点没有引用其前一个节点,
* 因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。
* */
    public static Node reverseList(Node head) {
     
        Node  curr=head;
        Node pre=null;
        while (curr!=null){
     
         Node next= curr.next;
         curr.next=pre;
         pre=curr;
         curr=next;
        }
        return  pre;

    }
  //递归法
  public  static Node reverse(Node head) {
     
        if(head == null || head.next == null)
            return head;
        Node ret = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return ret;
    }
//反转前n个结点
   public static Node successor = null; // 后驱节点(第 n + 1 个节点)

   public static Node reverseN(Node head, int n) {
     
        if (n == 1) {
     
            successor = head.next;
            return head;
        }
        // 以 head.next 为起点,需要反转前 n - 1 个节点
        Node ret = reverseN(head.next, n - 1);
        head.next.next = head;
        head.next = successor; // 将反转后的 head 与后面节点连接

        return ret;
    }


    public static void main(String[] args) {
     
        Node h = createNode();
        print(h);
        //反转前3个结点
        Node node = reverseN(h, 3);
        print(node);
        //
        Node reverse = reverse(node);
        print(reverse);
    }
}

``

你可能感兴趣的:(算法,链表,单链表,java)