import java.util.Scanner;
import java.util.Stack;
public class Janzhioffer {
/*
* 劍指offer第三題 倒着輸出鏈表
* 想法一:拷到一個數組,然後倒着輸出
* 想法二:拷到一個棧裏,然後出棧輸出
* 想法三:用一個遞歸
* 想法四:用一個頭插法(該方法會破壞原鏈表)
* 以下對想法二實現
*/
private static class Node
{
public int value = 0;
public Node next = null;
}
private static Node CreateLink()
{
Scanner sc = new Scanner(System.in);
Node head = new Node();
head.value = sc.nextInt();
Node nd = head;
for(int i = 0;i<8;i++)
{
Node node = new Node();
node.value = sc.nextInt();
nd.next = node;
nd = node;
}
return head;
}
private static void PrintLink(Node node)
{
if(node == null)
return;
PrintLink(node.next);
System.out.print(node.value+" ");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node head = CreateLink();
//以下是棧輸出
Stack<Node> stack = new Stack<>();
Node node = head;
while(node!=null)
{
stack.push(node);
node = node.next;
}
while(!stack.isEmpty())
{
System.out.print(stack.pop().value+" ");
}
//以下是用一個遞歸實現
System.out.println("");
PrintLink(head);
//以下是頭插法實現
System.out.println("");
node = head;
Node node1 = head.next;
if(node1 == null)
{
System.out.println(node.value);
return;
}
Node node2 = node1;
if(node2.next == null)
{
System.out.print(node1.value+" ");
System.out.println(node.value);
return;
}
while(node2!=null)
{
node1 = node2;
node2 = node2.next;
node1.next = node;
node = node1;
}
head.next = null;//這一步尤爲重要,否則它會形成一個環
head = node;
while(node!=null)
{
System.out.print(node.value+" ");
node = node.next;
}
/**/
//以下是頭插法頭結點爲空的鏈
System.out.println();
Node head1 = new Node();
Node p1 = head;
Node p2;
while(p1!=null)
{
p2 = p1;
p1 = p1.next;
p2.next = head1.next;
head1.next = p2;
}
head = head1.next;
node = head;
while(node!=null)
{
System.out.print(node.value+" ");
node = node.next;
}
}
}
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9