• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java实现移除链表元素操作

武飞扬头像
PHP中文网
帮助43

目的:移除链表元素

问题介绍:

删除链表中等于给定值 *「val*」 的所有节点。

示例描述:

示例:
 
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

题解思路:

一个是基于哨兵节点的方式进行解决,另一个是基于java集合的方式来做,本质上还是一样的

程序实现:

 import java.util.*;
 
public class RemoveElementsTest3 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(6);
        ListNode l4 = new ListNode(3);
        ListNode l5 = new ListNode(4);
        ListNode l6 = new ListNode(5);
        ListNode l7 = new ListNode(6);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        l6.next = l7;
        ListNode listNode = removeElements2(l1, 6);
        System.out.println("listNode = "   listNode);
 
    }
 
    public static ListNode removeElements(ListNode head, int val) {
        ListNode dummyNode = new ListNode(0);
        ListNode currentNode = dummyNode;
        while (head != null) {
            if (head.val != val) {
                currentNode.next = head;
                currentNode = currentNode.next;
            }
            head = head.next;
        }
        currentNode.next = null;
        return dummyNode.next;
    }
 
    public static ListNode removeElements2(ListNode head, int val) {
        List<Integer> list = new LinkedList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        List<Integer> tempList = new ArrayList<>();
        tempList.add(val);
        list.removeAll(tempList);
        ListNode dummyNode = new ListNode(0);
        ListNode tempNode = dummyNode;
        for (int i = 0, size = list.size(); i < size; i  ) {
            ListNode listNode = new ListNode(list.get(i));
            tempNode.next = listNode;
            tempNode = tempNode.next;
        }
        return dummyNode.next;
    }
}

总结:

其实,写到这我觉得你看看整个程序的实现逻辑是很容易看懂的吧,没有什么难点需要推导的,如果不懂的话,可以多调试调试给定的程序,每次输出的内容都是成功运行之后才输出的。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tangbcefk
系列文章
更多 icon
同类精品
更多 icon
继续加载