赞
踩
Eg:
链表:1->2->3->4 经过反转后 4->3->2->1
递归实现
public class FanZhuanList { public static void main(String[] args) { Node first = new Node(); Node second = new Node(); Node third = new Node(); Node forth = new Node(); first.data = 1; //初 first.next = second; second.data = 2; //始 second.next = third; third.data = 3; //化 third.next = forth; //链 forth.data = 4; forth.next = null; //表 Node k = first.reserseList(first);//反转的方法 k.getList(k); } } class Node{ int data; Node next; //反转函数 Node reserseList(Node head) { if(head == null || head.next == null) { return head; }//当链表是一个或者没有就应当直接返回 Node newList = reserseList(head.next); //创建一个新的链表,存放反转后的链表 Node t1 = head.next; //接下来这三步就是通过引入新的结点来反转链表 t1.next = head; head.next = null; return newList; } //输出函数 public void getList(Node node) { while(node != null) { System.out.println(node.data); node = node.next; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。