用递归逆序一个单链表

来源:互联网 发布:网络情歌对唱大全 编辑:程序博客网 时间:2024/05/12 15:05

题目描述

输入一个链表,反转链表后,输出链表的所有元素。
public class HeapPrint {public static ListNode ReverseList(ListNode head) {if (head == null||head.next == null) {return head;}ListNode q = head.next;ListNode ph = ReverseList(q);q.next = head;head.next = null;//对于非头节点来说有没有是一样的,因为之后会替换的,就是头结点会有用,防止死循环System.out.println("ph:"+ph.val);return ph;}public static void main(String[] args) {ListNode p1=new ListNode(1);ListNode p2=new ListNode(2);ListNode p3=new ListNode(3);ListNode p4=new ListNode(4);p1.next=p2;p2.next=p3;p3.next=p4;ListNode head=ReverseList(p1);while(head!=null){System.out.println(head.val);head=head.next;}}}class ListNode {int val;ListNode next = null;ListNode(int val) {this.val = val;}}
输出:
ph:4ph:4ph:44321
开始这个题目,真是迷糊,用顺序来做其实是很简单的。但是弄成递归来做,说实话对我来说不好理解,就写下来自己调试了一下。递归的函数我以为每次返回的东西都是不同的,没想到每次都返回相同的1->2->3->4调用之后都会返回最后一个,其他的都比较好理解了。还有就是
head.next = null;
这句话其实仅对于1这个节点有效。

第二种方法是我自己写的,思维上比较传统
public class HeapPrint2 {static ListNode newHead;public static ListNode ReverseList(ListNode head) {if (head == null)return head;ListNode returnV=Reverse(head);returnV.next=null;return newHead;}public static ListNode Reverse(ListNode head) {if (head.next == null) {newHead = head;return head;}ListNode tmp;tmp = Reverse(head.next);System.out.println("tmp:"+tmp.val);tmp.next = head;return head;}public static void main(String[] args) {ListNode p1 = new ListNode(1);ListNode p2 = new ListNode(2);ListNode p3 = new ListNode(3);ListNode p4 = new ListNode(4);p1.next = p2;p2.next = p3;p3.next = p4;ReverseList(p1);ListNode head = newHead;while (head != null) {System.out.println(head.val);head = head.next;}}}

第三,普通的逆序打印
public class ReversePrint {public static void ReversePrint(ListNode head){if(head.next==null){System.out.println(head.val);return;}ReversePrint(head.next);System.out.println(head.val);}public static void main(String[] args) {ListNode p1 = new ListNode(1);ListNode p2 = new ListNode(2);ListNode p3 = new ListNode(3);ListNode p4 = new ListNode(4);p1.next = p2;p2.next = p3;p3.next = p4;ReversePrint(p1);}}


0 0
原创粉丝点击