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

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

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

package newCoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author:凌曦
 * @Version:1.0
 * @Date:2022/7/25-22:45
 * @Description: 2 1 2 3 2 5 1 4 5 7 2
 * 1 2 表示为
 * 2->1
 * 链表为2->1
 * <p>
 * 3 2表示为
 * 2->3
 * 链表为2->3->1
 * <p>
 * 5 1表示为
 * 1->5
 * 链表为2->3->1->5
 * <p>
 * 4 5表示为
 * 5->4
 * 链表为2->3->1->5->4
 * <p>
 * 7 2表示为
 * 2->7
 * 链表为2->7->3->1->5->4
 */
public class OneWayListDelVal {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strings = br.readLine().split(" ");
        int delVal = Integer.parseInt(strings[strings.length - 1]);
        int len = Integer.parseInt(strings[0]);
        Node head = new Node(strings[1]);
        for (int i = 2; i < strings.length - 1; i += 2) {
            int search = Integer.parseInt(strings[i + 1]);
            Node insertNode = new Node(strings[i]);
            insertNode.insertAfter(head, search);
        }
        System.out.println(head.delNode(head, delVal).toString());
    }
}

class Node {
    int value;
    Node next;

    Node(String value) {
        this.value = Integer.parseInt(value);
    }

    Node delNode(Node head, int delValue) {
        Node temp = head;
        // 我就是要删头节点,那再见了,我给你我的下一个,江湖再见
        if (head.value == delValue) {
            return head.next;
        }
        // 不是,那我给你找
        // 下一个不为空?
        while (head.next != null) {
            // 他的值是你要的
            if (head.next.value == delValue) {
                // 让他滚,让他的下一个接应
                head.next = head.next.next;
                break;
            }
            // 没找到就往下走
            head = head.next;
        }
        return temp;
    }

    void insertAfter(Node head, int searchValue) {
        while (head != null) {
            if (head.value == searchValue) {
                // 顺序不能换
                // 我的下一个是你原来的下一个
                this.next = head.next;
                // 你的下一个就是我
                head.next = this;
                break;
            }
            head = head.next;
        }
        //找不到就插到最后
//        head.next = this;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node cur = this;
        while (cur != null) {
            sb.append(cur.value).append(" ");
            cur = cur.next;
        }
        return sb.toString();
    }
}

全部评论

相关推荐

11-13 20:16
已编辑
厦门理工学院 软件测试
专业嗎喽:硕佬,把学校背景放后面几段,学校背景双非还学院,让人看了就不想往下看。 把实习经历和个人奖项放前面,用数字化简述自己实习的成果和掌握的技能,比如负责项目一次通过率90%,曾4次发现项目潜在问题风险为公司减少损失等等
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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