package com.serein; public class ListReversal { private int[] _dataArray = null; public ListReversal(int[] dataArray) { this._dataArray = dataArray; } /** * create a single list * @return */ public ChildNode createSingleList() { if(null == this._dataArray || this._dataArray.length==0) { return null; } ChildNode head = new ChildNode(); head.data = this._dataArray[0]; ChildNode pro = head; for(int index=1; index<this._dataArray.length; index++) { ChildNode current = new ChildNode(); current.data = this._dataArray[index]; pro.next = current; pro = current; } return head; } /** * reversal single list * @param head * @return */ public ChildNode reversalSingleList(ChildNode head) { if(null == head) { return null; } ChildNode current = head; ChildNode pro = null; ChildNode next = null; while(null != current) { next = current.next; current.next = pro; pro = current; current = next; } return pro; } public ChildNode recursionSingleList(ChildNode current, ChildNode pro) { if(null == current) { return pro; } ChildNode next = current.next; current.next = pro; return recursionSingleList(next, current); } public class ChildNode { public ChildNode next = null; public int data = -1; } public class DoubleChildNode { public DoubleChildNode pro = null; public DoubleChildNode next = null; public int data = -1; } public DoubleChildNode createDoubleList() { if(null == this._dataArray || this._dataArray.length==0) { return null; } DoubleChildNode head = new DoubleChildNode(); head.data = this._dataArray[0]; DoubleChildNode pro = head; for(int index=1; index<this._dataArray.length; index++) { DoubleChildNode current = new DoubleChildNode(); current.data = this._dataArray[index]; pro.next = current; current.pro = pro; pro = current; } return head; } public DoubleChildNode recursionDoubleList(DoubleChildNode current, DoubleChildNode pro) { if(null == current) { return pro; } DoubleChildNode next = current.next; current.next = current.pro; current.pro = next; return recursionDoubleList(next, current); } public DoubleChildNode reversalDoubleList(DoubleChildNode head) { if(null == head) { return null; } DoubleChildNode current = head; DoubleChildNode next = null; while(null != current) { next = current.next; current.next = current.pro; current.pro = next; if(null == next) { head = current; } current = next; } return head; } public static void main(String[] args) { System.out.println("This is a test!"); int[] dataArray = {1, 3, 5, 6, 7, 8}; ListReversal lr = new ListReversal(dataArray); ListReversal.ChildNode node = lr.createSingleList(); ListReversal.ChildNode nodeReversal = lr.reversalSingleList(node); ListReversal.ChildNode nodeRecursionReversal = lr.recursionSingleList(nodeReversal, null); ListReversal.DoubleChildNode doubleNode = lr.createDoubleList(); ListReversal.DoubleChildNode doubleNodeReversal = lr.reversalDoubleList(doubleNode); ListReversal.DoubleChildNode doubleNodeRecursionReversal = lr.recursionDoubleList(doubleNodeReversal, null); } }