剑指offer之倒着输出链表 Java

package fenshujs;


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 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值