Java实现创建链表与打印链表元素(可作为模板)

1、通过数组元素值,构造一个单向链表;

2、将链表元素以数组的形式打印出来,如“[1, 2, 3, 4]”

package listnodes;

//创建节点类
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class RemoveElements {

    public static void main(String[] args) {

        //构造链表
        int[] nums = new int[]{1,2,2,1};
        ListNode head = null;
        //按照从后往前的顺序遍历数组,最终构造出一个链表
        for (int i = nums.length - 1; i >= 0; i--) {
            ListNode node = new ListNode(nums[i]);
            if(head != null){
                node.next = head;
            }
            head = node;
        }

        //处理链表
        Solution sol = new Solution();
        ListNode resNode = sol.removeElements(head, 2);

        //遍历链表并打印
        StringBuilder sb = new StringBuilder("[");
        while(resNode != null){
            if(sb.length() != 1) sb.append(", ");
            sb.append(resNode.val);
            resNode = resNode.next;
        }
        sb.append("]");
        System.out.println(sb);//[1, 1]
    }
}


class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
}

你可能感兴趣的:(Java精修,数据结构与算法,java,链表,数据结构,构造链表,打印链表元素)