0x01链表反转

/**
 * 0x01
 *      链表反转
 * @author Green.Gee
 * @date 2022/4/22 14:07
 * @email [email protected]
 */
public class SolveQ7 {

    public static void main(String[] args) {
        //初始化链表
        GeeListNode node = new GeeListNode(1);
        node.add(2);
        node.add(3);
        node.add(4);
        node.add(5);

        GeeListNode.print(node);
        System.err.println("=========================");
        GeeListNode.print(reverseList(node));
    }

    // 单链表翻转
    public static GeeListNode rollListNode(GeeListNode head){
        GeeListNode pre = head;//上一个节点
        GeeListNode current = head.next;//当前节点
        while(current != null){
            GeeListNode next = current.next;// 暂存当前指针
            current.next = pre;// 下一个节点指向上一个节点 ————改变指针方向
            pre = current;// 上一个节点的下一个节点指针改变成当前节点 完成翻转
            current = next;// 复原原始指针顺序
        }
        head.next = null;// 避免打印出现链表环
        return pre;
    }

    // 递归版
    public static GeeListNode reverseList(GeeListNode head) {
        if(head==null||head.next==null)//如果最后一个节点不操作
            return  head;
        GeeListNode node = reverseList(head.next);//先递归 到最底层 然后返回
        head.next.next = head;//后面一个节点指向自己
        head.next = null;//自己本来指向的next置为null
        return node;//返回最后一个节点(一直被递归传递)
    }
}


/**
 * 单链表
 */
class  GeeListNode {

    public Object val;
    public GeeListNode next;

    public GeeListNode(Object val) {
        this.val = val;
    }

    // 添加
    public boolean add(Object val){
        GeeListNode node = new GeeListNode(val);
        if(this.next == null){
            this.next = node;
        }else{
            this.next.add(val);
        }
        return true;
    }

    // print
    public void print(){
        System.err.println(this.val +"\t");
        if(this.next != null){
            this.next.print();
        }
    }
    public static void print(GeeListNode node){
        System.err.println(node.val +"\t");
        if(node.next != null){
            node.next.print(node.next);
        }
    }
}

你可能感兴趣的:(算法【,Hard,Code】,算法)