1、通过数组元素值,构造一个单向链表;文章来源:https://www.toymoban.com/news/detail-745685.html
2、将链表元素以数组的形式打印出来,如“[1, 2, 3, 4]”文章来源地址https://www.toymoban.com/news/detail-745685.html
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实现创建链表与打印链表元素(可作为模板)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!