反向打印单链表

package com.study;

/**
* 从尾到头打印单链表
* */
class Node {
public int data;
public Node next;
public Node() {

}
}

class Stack {

private static final int MAXSIZE = 10;

private static int point = 0; //指向栈顶

private static int[] arr = new int[MAXSIZE];

public static void push(int data) {
if(point < MAXSIZE) {
arr[point] = data;
point++;
}
else {
System.out.println("The stack is full");
}
}

public static int pop() {
if( point > 0) {
point--;
return arr[point];
}
else {
return -1;
}
}
}

public class suanfa3 {

private static int[] arr = {1,2,3,4,5};

/根据数组创建单链表/
public static void CreateList(int[] arr, Node head) {
if(head != null) {
for(int i = 0; i < arr.length; i++) {
Node node = new Node();
node.data = arr[i];
node.next = head.next;
head.next = node;
}

}
}

/顺序打印单链表/
public static void PrintList(Node head) {
Node pNode;//游标
if(head != null) {
while(head.next != null) {
pNode = head.next;
System.out.print(pNode.data+"-->");
head = head.next;
}
System.out.println("NULL");
}
}

/*不改变原来的链表结构打印,可以考虑以空间换取时间来提高效率**/
public static void ReversePrintWithoutChange(Node head) {

int data;
/*入栈**/
while(head.next != null) {
Stack.push(head.next.data);
head = head.next;
}

/出栈/

while((data = Stack.pop()) != -1) {
System.out.print(data + "-->");
}

System.out.println("NULL");
}

public static void main(String[] args) {
Node node = new Node();
CreateList(arr,node);
PrintList(node);
ReversePrintWithoutChange(node);
}

}

因为是单链表,所以无法遍历到尾节点,然后在倒回去打印。这里有两种解决思路:

1.不改变该链表结构的情况下,由于先遍历到的节点后打印,所以符合栈的特点,所以自然想到可以建立一个栈存储先遍历到的节点。然后再出栈即可。如上面的代码所示。

2.先逆转单链表,然后再顺次遍历,但是这样会改变原来的链表结构。关于逆转单链表,请参考本博客的其他文章。

posted @ 2015-07-01 15:35  高适  阅读(844)  评论(0)    收藏  举报