java 数组与链表_Java将数组与链表的互换

package 链表;

import java.util.ArrayList;

class Node{

int val;

Node next;

Node(int val){

this.val = val;

}

}

public class Main1 {

public static Node arrayToNode(int[] arr){

Node head = new Node(arr[0]); // 把数组的第一个位置定义为头结点

Node other = head; // 一个指针,此时指向头结点

for(int i=1;i

Node temp = new Node(arr[i]);

other.next = temp;

other = other.next;

}//在此处打印结点容易导致head的变化

return head;

}

public static void printNode(Node node){

while(node!=null){

System.out.print(node.val+" ");

node = node.next;

}

}

public static void nodeTolist(Node node){

ArrayList list = new ArrayList<>();

while(node != null){

list.add(node.val);

node = node.next;

}

System.out.println();

System.out.println(list);

}

public static void main(String[] args){

int[] arr = new int[]{1,2,3,4,5,6};

Node node = arrayToNode(arr);

printNode(node);

nodeTolist(node);

}

}

标签:Node,node,arr,Java,val,int,链表,互换,new

来源: https://blog.csdn.net/qq_38826019/article/details/101097823

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值