package dataconfig;
/****
* 链表建立,逆序输出
* */
public class PrintfLinkTailbegin {
/*构建链表*/
static class Node{
public int data; //值
public Node next; //结点
}
public static Node createLink(int a[]){
Node head = null,tail = null; //头结点,尾结点
int i=0;
if (a.length < 1){ //判断给定数组是否符合要求
return null;
}
while(i<a.length){
Node node = new Node(); //创建新节点、赋值、指向下一个结点
node.data = a[i];
node.next = null;
if (head == null){
head = tail = node;
} else {
tail = tail.next = node; //挂链,tail向尾移动
}
i++;
}
return head;
}
/*遍历链表*/
public static void printLink(Node node){
while(node != null){
System.out.print(node.data+"\t");
node = node.next;
}
System.out.println();
}
/*逆序输出,递归----实质栈*/
public static void Recursivereverse(Node node){
if (node != null){
if (node.next != null){
Recursivereverse(node.next);
}
System.out.print(node.data+"\t");
}
}
public static void main(String[] args) {
int a[] = {3,2,5,8,4,7,6,9};
Node link = createLink(a);
printLink(link);
Recursivereverse(link);
System.out.println();
}
}
Java单向链表,不带表头
最新推荐文章于 2022-03-15 11:24:21 发布