单链表反转java

public class SingleLinkTest {

    public static void main(String[] args) {
    Node node = new Node(0);
    Node head = node;
    int i = 1;
    while(i < 10){
        node.next = new Node(i);
        node = node.next;
        i++;
    }
    Node cur = head;
    while(cur != null){
        System.out.print(cur.data + ",");
        cur = cur.next;
    }


    System.out.println("反转后");
    head = reverse(head);
    cur = head;
    while(cur != null){
        System.out.print(cur.data + ",");
        cur = cur.next;
    }


    System.out.println("反转后");
    head = reverseNoDiGui(head);
    cur = head;
    while(cur != null){
        System.out.print(cur.data + ",");
        cur = cur.next;
    }
    }

    public static Node reverse(Node node){
    if(node == null || node.next == null){
        return node;
    }
    Node reHead = reverse(node.next);
    node.next.next = node;
    node.next = null;
    return reHead;
    }

    public static Node reverseNoDiGui(Node head){
    Node pre = head;
    Node cur = head.next;
    Node temp;
    while(cur != null){
        temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    head.next = null;
    return pre;
    }
}

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

    public int data;
    public Node next;
}

你可能感兴趣的:(数据结构算法)