java如何构建、打印链表

前面的话

要想使用java语言在本地测试链表相关的算法,必须自己写一个测试代码。

测试代码

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class CreateList {
	// 创建链表
	public static ListNode create(int arr[], int n) {
		if(n == 0 ) {
			return null;
		}
		// 将数组的第一个元素赋给头指针
		ListNode head =  new ListNode(arr[0]);
		ListNode curNode = head;
		// 依次赋值
		for(int  i = 1; i < n;i++) {
		    curNode.next = new ListNode(arr[i]);
			curNode = curNode.next;
		}
		return head;
	}
	// 打印链表
	public static void printList(ListNode head) {
		ListNode curNode = head;
		while(curNode != null) {
			System.out.print(curNode.val + "->");
			curNode = curNode.next;
		}
		System.out.print("NULL");
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {1, 4, 8, 3, 2};
		ListNode head = create(arr, 5);
		printList(head);
	}

}

测试结果:
在这里插入图片描述

发布了229 篇原创文章 · 获赞 169 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41257129/article/details/104010196