Programming|在单链表中删除指定值的节点-解法一(Java)

【Programming|在单链表中删除指定值的节点-解法一(Java)】分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请轻击http://www.captainbed.net

package live.every.day.CodingInterviewGuide.List; import java.util.Stack; /** * 题目: * 在单链表中删除指定值的节点。 * * 思路: * 利用栈或其他容器收集节点。 * * @author Created by LiveEveryDay */public class RemoveNodeInListSolution1 {public static class Node { public int data; public Node next; public Node(int data) { this.data = https://www.it610.com/article/data; } }public static Node removeNode(Node head, int data) { Stack stack = new Stack<>(); while (head != null) { if (head.data != data) { stack.push(head); } head = head.next; } while (!stack.isEmpty()) { stack.peek().next = head; head = stack.pop(); } return head; }public static void main(String[] args) { Node node1 = new Node(1); Node node2 = new Node(3); Node node3 = new Node(2); Node node4 = new Node(3); Node node5 = new Node(1); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; removeNode(node1, 3); Node n = node1; while (n != null) { System.out.printf("%d ", n.data); n = n.next; }} }// ------ Output ------ /* 1 2 1 */

    推荐阅读