题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            Main a = new Main();
            a.delete(str);
        }
    }

    public void delete (String str) {
        String[] s = str.split(" ");
        int n = Integer.parseInt(s[0]);
        ListNode head = new ListNode(Integer.parseInt(s[1]), null);
        int target = Integer.parseInt(s[s.length - 1]);
        ListNode vhead = new ListNode();
        vhead.nextNode = head;
	  
        for (int i = 2; i < n * 2 - 1; i += 2) {
            int newValue = Integer.parseInt(s[i]); //2 , 4, 6
            int preValue = Integer.parseInt(s[i + 1]);//3, 5, 7
            ListNode newNode = new ListNode(newValue, null);
            ListNode start = vhead.nextNode;
            while (start != null) {
                ListNode cur = start;
                int value1 = cur.value;
                if (value1 == preValue) {
                    ListNode temp = cur.nextNode;
                    cur.nextNode = newNode;
                    newNode.nextNode = temp;
                }
                start = start.nextNode;
            }
        }
        //删除目标节点
        ListNode deleteIndex = vhead;
        while (deleteIndex != null && deleteIndex.nextNode != null) {
            int value = deleteIndex.nextNode.value;
            if (value == target) {
                deleteIndex.nextNode = deleteIndex.nextNode.nextNode;
            }
            deleteIndex = deleteIndex.nextNode;
        }

        while (vhead != null && vhead.nextNode != null) {
            System.out.print(vhead.nextNode.value + " ");
            vhead = vhead.nextNode;
        }

    }
    class ListNode {
        int value;
        ListNode nextNode;
        public ListNode() {
        }

        public ListNode(int value, ListNode nextNode) {
            this.value = value;
            this.nextNode = nextNode;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public ListNode getNextNode() {
            return nextNode;
        }

        public void setNextNode(ListNode nextNode) {
            this.nextNode = nextNode;
        }
    }
}

全部评论

相关推荐

Lorn的意义:你这种岗位在中国现在要么牛马天天加班,要么关系户进去好吃好喝,8年时间,真的天翻地覆了,对于资本来说你就说一头体力更好的牛马,哎,退伍没有包分配你真的亏了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务