public class Demo5 {
static void printlist_recursive(LinkNode head){
if(head != null)
{
if(head.next != null)
{
printlist_recursive(head.next);
}
System.out.print(head.value);
}
}
public static void main(String[] args) {
LinkList list=new LinkList();
LinkNode node1=list.createNode(1);
LinkNode node2=list.createNode(2);
LinkNode node3=list.createNode(3);
LinkNode node4=list.createNode(4);
LinkNode node5=list.createNode(5);
list.connectNode(node1, node2);
list.connectNode(node2, node3);
list.connectNode(node3, node4);
list.connectNode(node4, node5);
list.printlist(node1);
printlist_recursive(node1);
}
}
class LinkNode {
public int value;
public LinkNode next;
public LinkNode() {
super();
// TODO Auto-generated constructor stub
}
public LinkNode(int value) {
super();
this.value = value;
}
public void display() // display ourself
{
System.out.print(value);
}
}
class LinkList
{
LinkNode createNode(int value)
{
LinkNode node=new LinkNode(value);
node.next=null;
return node;
}
void connectNode(LinkNode current,LinkNode next)
{
if(current == null)
{
System.out.println("Error to connect two nodes.");
}
current.next=next;
}
void printlist(LinkNode head)
{
LinkNode node=head;
while(node != null){
System.out.print(node.value);
node=node.next;
}
System.out.println("");
}
}
面试题5:从尾到头打印链表
最新推荐文章于 2021-12-20 21:51:43 发布