剑指offer——链表的递归反转打印

来源:互联网 发布:淘宝店铺怎么增加分类 编辑:程序博客网 时间:2024/06/06 03:25

题目:输入一个链表的头结点,从头到尾反向打印出每个结点的值

这里主要考查的是链表的知识,反向反转如果不考虑更改链表的结构时,可以考虑非递归的直接倒置算法,这里我们主要考虑递归方法的反转打印

递归思想是先按照顺序将指针指向链表的最后然后将nextNode的next指向前一个位置的指针,把前一个位置的值加到最后,最后时限倒置

public static class Node{ //声明链表        int value;  //设置链表的值        Node next;  //设置链表指针        public Node(int n){              this.value=n;              this.next=null;          }  
public Node ReverList(Node head){    if(head==null||head.next==null) return head;//如果链表为空或者链表只有一个头结点,则直接返回该链表    Node nextNode=head.next;//将nextNode指向head.next    head.next=null;//将head.next设置为空    ReverList(nextNode);//递归调用    nextNode.next=head;//开始倒置    return head;//返回链表    }



原创粉丝点击