android面试题--单链表反转

 

  

  

//定义链表类
  class Node{
        int data;
        Node next;
    }
    void main(){
     //第一步:新建链表
        Node five = new Node();
        five.data = 5;
        five.next = null;

        Node four = new Node();
        four.data = 4;
        four.next = five;

        Node three = new Node();
        three.data = 3;
        three.next = four;

        Node two = new Node();
        two.data = 2;
        two.next = three;

        Node one = new Node();
        one.data = 1;
        one.next = two;
     //开始反转
        reverseNode(one);
    }

    Node reverseNode(Node head) {
        if (head.next == null) {
            return head;
        }
        Node newNode = reverseNode(head.next);
        head.next.next = head;
        head.next = null;
        return newNode;
    }

 

posted @ 2022-09-30 14:16  野生野鸡码农  阅读(58)  评论(0编辑  收藏  举报