从尾到头打印一个链表
1、利用jdk的链表数据结构实现:
/** * 问题7、从尾到头打印列表 用jdk的LinkList * */ @Test public void print_reverse_LinkedList(){ LinkedList<Person> list = new LinkedList<Person>(); for (int i =5;i>0;i--){ Person p1 = new Person(); p1.setName("Alice"+i); p1.setAge(10+i); list.add(p1); } // 利用栈 实现逆序打印链表的内容 Stack<Person> stack = new Stack<Person>(); while (!list.isEmpty()){ Person p2 = list.getFirst(); list.removeFirst(); stack.push(p2); } while (!stack.isEmpty()){ Person p = stack.pop(); System.out.println(p.toString()); } }
2、自定义单链表,实现从尾到头打印链表
2.1数据结构的定义:
2.1.1链表的定义:
package com.itmei.offer; /** * Created by qiaodan on 2017/12/8. */ public class MyLinkedList<T> { int size; MyLinkedListNode<T> head; MyLinkedListNode<T> rear; public MyLinkedListNode<T> getRear() { return rear; } public void setRear(MyLinkedListNode<T> rear) { this.rear = rear; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public MyLinkedListNode<T> getHead() { return head; } public void setHead(MyLinkedListNode<T> head) { this.head = head; } public MyLinkedList() { this.size = 0; this.head= null; this.rear = null; } public MyLinkedList add(T t){ MyLinkedListNode<T> node = new MyLinkedListNode<>(t); if (this.head==null){ this.head = node; this.size = 1; this.rear = node; return this; }else { this.rear.next = node; this.rear = node; this.size = this.size+1; return this; } } public boolean isEmpty(){ if (this.size==0&&this.head==null) return true; else return false; } public T getFirst(){ if (this.head!=null&&this.size>0) return this.head.getData(); else return null; } public boolean removeFirst(){ if (this.head.next==null){ this.head =null; this.size =0; return true; }else { this.head = this.head.next; this.size= this.size-1; return true; } } }
2.1.2链表节点的定义:
package com.itmei.offer; /** * Created by qiaodan on 2017/12/8. */ public class MyLinkedListNode<T> { T data; MyLinkedListNode<T> next; public T getData() { return data; } public void setData(T data) { this.data = data; } public MyLinkedListNode<T> getNext() { return next; } public void setNext(MyLinkedListNode<T> next) { this.next = next; } public MyLinkedListNode(T data) { this.data = data; this.next = null; } }
2.2 倒叙遍历的实现:
2.2.1实现的主方法:
/** * 问题8、从尾到头打印列表 自定义的MyLinkList 有next指针 可以直接用递归的方式来打印链表 * */ @Test public void print_reverse_MyLinkedList() { MyLinkedList<Person> list = new MyLinkedList<>(); for (int i = 5; i > 0; i--) { Person p1 = new Person(); p1.setName("Alice" + i); p1.setAge(10 + i); list.add(p1); } // 利用递归来打印 if (list==null){ System.out.println("链表为空!"); }else { print_reverse_MyLinkedList(list.head); } }
2.2.2实现的核心递归方法:
// 递归动作 这里还有一个问题 为什么没有按照预期 倒叙打印 反而只打印了链表的尾部 一个else的区别 递归打印下面的元素之后 回来要打印自己! public void print_reverse_MyLinkedList(MyLinkedListNode head){ if (head.next!=null) this.print_reverse_MyLinkedList(head.next); System.out.println(head.getData().toString()); }