逆置链表
public class InterViewQuestion_ReverseLinkList {
public static int[] reversePrint(ListNode head) {
/*题目描述:将链表逆置以数组的形似返回
*解题思路:
* 创建栈(以ArrayList的形式)
* 遍历链表,取值入栈
* 栈中元素逐个出栈放入结果集
*时间复杂度:2n
*空间复杂度:2n
* */
//创建栈
ArrayList<Integer> stack=new ArrayList<Integer>();
int top=0;
//遍历链表,元素入栈
while(head!=null) {
stack.add(top, Integer.valueOf(head.val));
top++;
head=head.next;
//if(head.next==null) break;
}
//创建结果集
int[] resultSet=new int[stack.size()];
//栈中元素逐个出栈 放入结果集
for(int i=0;i<resultSet.length;i++) {
top--;
resultSet[i]=stack.get(top);
}
return resultSet;
}
public static void main(String[] args) {
/*创建列表,使用reversePrint()方法逆置
* */
ListNode head = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(3);
head.next=node1;
node1.next=node2;
int[] result=InterViewQuestion_ReverseLinkList.reversePrint(head);
for(int element:result) {
System.out.println(element);
}
}
}
class ListNode {
int val;
ListNode next;
public ListNode() {
// TODO Auto-generated constructor stub
}
ListNode(int x) {
val = x;
}
}