题目:输入一个链表的头节点,从尾到头反过来打印出每个系欸但的值。链表节点定义如下 本实现方法有头节点,头节点没有数据域
class Node{
int value;
Node next;
public Node() {
}
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node [value=" + value + "]";
}
}
第一种方法:使用栈结构打印
public void PrintListReversingly_IterativeLy(){
if(head==null || head.next==null){
throw new IllegalArgumentException("头节点为空,或链表为空");
}
Stack<Node> stack = new Stack<Node>();
Node temp=head.next;
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
while(!stack.empty()){
System.out.println(stack.pop());
}
}
第二种:利用递归方法从尾到头
public void PrintListReversingly_Recursively(Node head){
if(head!=null){
if(head.next.next!=null){
PrintListReversingly_Recursively(head.next);
}
System.out.println(head.next);
}
}
完整源代码:
package com.basic;
import java.util.Scanner;
import java.util.Stack;
public class Queue_01 {
private static Node head=new Node(0);
public static void main(String[] args) {
Queue_01 queue = new Queue_01();
Scanner sc=new Scanner(System.in);
boolean isOK=true;
while(isOK){
System.out.println("输入 1 添加链表节点 2反序打印链表 3递归遍历 4退出");
char c=sc.next().charAt(0);
switch (c) {
case '1':
try{
System.out.println("请输入想要添加的节点数字");
String i=sc.next();
Queue_01.Node node = new Queue_01.Node(Integer.parseInt(i));
queue.AddByOrder(node);
}catch(Exception e){
System.out.println(e.getMessage());
}
break;
case '2':
try{
queue.PrintListReversingly_IterativeLy();
}catch(Exception e){
System.out.println(e.getMessage());
}
break;
case '3':
queue.PrintListReversingly_Recursively(head);
break;
case '4':
isOK=false;
break;
}
}
}
public void AddByOrder(Node newNode){
if(newNode==null){
throw new IllegalArgumentException("传入节点有误,添加失败");
}
Node temp=head;
boolean isOK=false;
while(true){
if(temp.next==null){
break;
}else if(temp.next.value==newNode.value){
isOK=true;
break;
}else if(temp.next.value > newNode.value){
break;
}
temp=temp.next;
}
if(!isOK){
newNode.next=temp.next;
temp.next=newNode;
}
}
public void PrintListReversingly_IterativeLy(){
if(head==null || head.next==null){
throw new IllegalArgumentException("头节点为空,或链表为空");
}
Stack<Node> stack = new Stack<Node>();
Node temp=head.next;
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
while(!stack.empty()){
System.out.println(stack.pop());
}
}
public void PrintListReversingly_Recursively(Node head){
if(head!=null){
if(head.next.next!=null){
PrintListReversingly_Recursively(head.next);
}
System.out.println(head.next);
}
}
static class Node{
int value;
Node next;
public Node() {
}
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node [value=" + value + "]";
}
}
}
此代码思路参考剑指offer 面试题
|