首页 > 试题广场 >

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

[编程题]从单向链表中删除指定值的节点
  • 热度指数:140832 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}定义一种单向链表的构造方法如下所示:
\hspace{23pt}\bullet\,先输入一个整数 n ,代表链表中节点的总数;
\hspace{23pt}\bullet\,再输入一个整数 h ,代表头节点的值;
\hspace{23pt}\bullet\,此后输入 n-1 个二元组 \left(a, b\right) ,表示在值为 b 的节点后插入值为 a 的节点。
\hspace{15pt}除此之外,保证输入的链表中不存在重复的节点值。

\hspace{15pt}现在,对于给定的链表构造方法和一个额外的整数 k ,你需要先按照上述构造方法构造出链表,随后删除值为 k 的节点,输出剩余的链表。

输入描述:
\hspace{15pt}在一行上:
{\hspace{20pt}}_\texttt{1.}\,先输入一个整数 n \left(1 \leqq n \leqq 10^3\right) 代表链表中节点的总数;
{\hspace{20pt}}_\texttt{2.}\,随后输入一个整数 h \left(1 \leqq h \leqq 10^4\right) 代表头节点的值;
{\hspace{20pt}}_\texttt{3.}\,随后输入 n-1 个二元组 \left(a, b\right) \left(1 \leqq a, b \leqq 10^4\right)
{\hspace{20pt}}_\texttt{4.}\,最后输入一个整数 k ,代表需要删除的节点值。

\hspace{15pt}除此之外,保证每一个 b 值在输入前已经存在于链表中;每一个 a 值在输入前均不存在于链表中。节点的值各不相同。


输出描述:
\hspace{15pt}在一行上输出 n-1 个整数,代表删除指定元素后剩余的链表。
示例1

输入

5 2 3 2 4 3 5 2 1 4 3

输出

2 5 4 1

说明

\hspace{15pt}在这个样例中,链表的构造过程如下:
\hspace{23pt}\bullet\,头节点为 2 ,得到链表 \left[{\color{orange}{\bf 2}}\right]
\hspace{23pt}\bullet\,2 后插入 3 ,得到链表 \left[2, {\color{orange}{\bf 3}}\right]
\hspace{23pt}\bullet\,3 后插入 4 ,得到链表 \left[2, 3, {\color{orange}{\bf 4}}\right]
\hspace{23pt}\bullet\,2 后插入 5 ,得到链表 \left[2, {\color{orange}{\bf 5}}, 3, 4\right]
\hspace{23pt}\bullet\,4 后插入 1 ,得到链表 \left[2, 5, 3, 4, {\color{orange}{\bf 1}}\right]
\hspace{15pt}随后,删除值为 3 的节点,得到链表 \left[2, 5, 4, 1\right]
示例2

输入

6 2 1 2 3 2 5 1 4 5 7 2 2

输出

7 3 1 5 4

说明

\hspace{15pt}在这个样例中,链表的构造过程如下:
\hspace{23pt}\bullet\,头节点为 2 ,得到链表 \left[{\color{orange}{\bf 2}}\right]
\hspace{23pt}\bullet\,2 后插入 1 ,得到链表 \left[2, {\color{orange}{\bf 1}}\right]
\hspace{23pt}\bullet\,2 后插入 3 ,得到链表 \left[2, {\color{orange}{\bf 3}}, 1\right]
\hspace{23pt}\bullet\,1 后插入 5 ,得到链表 \left[2, 3, 1, {\color{orange}{\bf 5}}\right]
\hspace{23pt}\bullet\,5 后插入 4 ,得到链表 \left[2, 3, 1, 5, {\color{orange}{\bf 4}}\right]
\hspace{23pt}\bullet\,2 后插入 7 ,得到链表 \left[2, {\color{orange}{\bf 7}}, 3, 1, 5, 4\right]
\hspace{15pt}随后,删除值为 2 的节点,得到链表 \left[7, 3, 1, 5, 4\right]

备注:
\hspace{15pt}本题由牛客重构过题面,您可能想要阅读原始题面,我们一并附于此处。
\hspace{15pt}【以下为原始题面】

输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。

链表的值不能重复。

构造过程,例如输入一行数据为:
6 2 1 2 3 2 5 1 4 5 7 2 2
则第一个参数6表示输入总共6个节点,第二个参数2表示头节点值为2,剩下的2个一组表示第2个节点值后面插入第1个节点值,为以下表示:
1 2 表示为
2->1
链表为2->1

3 2表示为
2->3
链表为2->3->1

5 1表示为
1->5
链表为2->3->1->5

4 5表示为
5->4
链表为2->3->1->5->4

7 2表示为
2->7
链表为2->7->3->1->5->4

最后的链表的顺序为 2 7 3 1 5 4

最后一个参数为2,表示要删掉节点为2的值

删除 结点 2

则结果为 7 3 1 5 4

数据范围:链表长度满足  ,节点中的值满足 

测试用例保证输入合法

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        Node head = new Node(in.nextInt());
        for (int i = 0; i < n - 1; i++) {
            Node newNode = new Node(in.nextInt());
            int father = in.nextInt();
            Node cur = head;
            while (cur != null) {
                if (cur.val != father)
                    cur = cur.next;
                else {
                    Node next = cur.next;
                    cur.next = newNode;
                    newNode.next = next;
                    break;
                }
            }
        }
        int del = in.nextInt();
        Node cur = head;
        while (cur.next != null) {
            if (cur.next.val != del)
                cur = cur.next;
            else {
                cur.next = cur.next.next;
                break;
            }
        }
        cur = head;
        StringBuilder sb = new StringBuilder();
        while (cur != null) {
            sb.append(cur.val).append(" ");
            cur = cur.next;
        }
        System.out.println(sb.deleteCharAt(sb.length() - 1));
    }
    public static class Node {
        public int val;
        public Node next;
        public Node(int val) {
            this.val = val;
        }
    }
}
发表于 2025-08-27 12:51:01 回复(0)
正常流程应该是手撕链表,但这里用集合ArrayList<Integer>模拟链表插入、删除了。注意方法Arrays.add(index, value)和Arrays.indexOf(value);
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int head = in.nextInt();
            List<Integer> res = new ArrayList<>();
            res.add(head);
            for (int i = 0; i < n - 1; i++) {
                int cutInValue = in.nextInt();
                int cutInAtValue = in.nextInt();
                res.add(res.indexOf(cutInAtValue) + 1, cutInValue);
            }
            int deleteValue = in.nextInt();
            for (int i = 0; i < res.size(); i++) {
                if (res.get(i) == deleteValue) {
                    res.remove(i);
                    i = i - 1;
                } else {
                    System.out.print(res.get(i) + " ");
                }
            }
        }
    }
}

发表于 2025-07-20 18:24:35 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int len = in.nextInt();
        Node head = new Node(in.nextInt());
        Map<Integer, Node> map = new HashMap<>();
        map.put(head.val, head);
        for (int i = 1; i < len; i++) {
            Node node = new Node(in.nextInt());
            Node frist = map.get(in.nextInt());
            Node seconde = frist.next;
           

            node.next = seconde;
            frist.next = node;
            map.put(node.val, node);
        }
        int target = in.nextInt();
        Node node = head;
        while (node != null) {
            if (node.val != target) {
                System.out.print(node.val + " ");
            }
            node = node.next;
        }
    }
}

class Node {
    int val;
    Node next;
    Node(int val) {
        this.val = val;
    }
}
发表于 2025-06-12 15:58:21 回复(0)
确定好索引位置就简单了
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        int h = in.nextInt();
        ArrayList<Integer> list = new ArrayList<>();
        list.add(h);
        for(int i=0;i<n-1;i++){
            int a = in.nextInt();
            int b = in.nextInt();
            list.add(list.indexOf(b)+1,a);
        }
        int k = in.nextInt();
        list.remove(list.indexOf(k));
        for(int i : list){
            System.out.print(i+" ");
        }
    }
}


发表于 2025-05-29 01:28:43 回复(0)
删除节点没有首尾判断 已通过
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int numberOfNodes = scanner.nextInt();
        Node firstNode = new Node(scanner.nextInt(), null);
        int curE = 0;
        int preE = 0;
        int count = 0;
        for (int i = 0; i < (numberOfNodes - 1); i++) {
            curE = scanner.nextInt();
            preE = scanner.nextInt();
            Node newNode = new Node(curE, null);
            if (count == 0) {
//                System.out.println(newNode+"即将插入_"+i);
//                System.out.println(newNode+"插入成功");
                count++;
                firstNode.setNext(newNode);
            } else {
//                System.out.println(newNode+"即将插入_"+i);
                Node temp = firstNode;
                while (temp != null) {
                    if (temp.getE() == preE) {
                        newNode.setNext(temp.getNext());
                        temp.setNext(newNode);
                        /*System.out.println("两值相同进行插入 "+temp.getE()+" "+preE+" while循环的结束条件"+temp.getNext());
                        System.out.println(newNode+"插入成功"+" "+i);*/
                        break;
                    }
                    temp = temp.getNext();
                }
            }
        }

        //记录要删除的节点
        int k = scanner.nextInt();
//        System.out.println("要删除的节点" + k);
        Node temp1 = firstNode;
        Node oldNode = firstNode;
        while (temp1 != null) {
//            System.out.println(temp1.getE());
            if (temp1.getE() == k) {
                /*System.out.println(oldNode);
                System.out.println(temp1);*/
                oldNode.setNext(temp1.getNext());
                temp1.setNext(null);
            }
            oldNode = temp1;
            temp1 = temp1.getNext();
        }

        //遍历输出链表
        Node temp2 = firstNode;
        while (temp2 != null) {
            System.out.print(temp2.getE() + " ");
            temp2 = temp2.getNext();
        }
    }
}

class Node {
    private int e;
    private Node next;

    public Node(int e, Node node) {
        this.e = e;
        this.next = node;
    }

    public int getE() {
        return e;
    }

    public void setE(int e) {
        this.e = e;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
               "e=" + e +
               ", next=" + next +
               '}';
    }
}
发表于 2025-04-21 15:59:01 回复(0)
题目只要求输出值,那我不用链表直接使用列表模拟他不炸了吗
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n=in.nextInt();
        int h=in.nextInt();
        int [][]create=new int[n-1][2];
        for(int i=0;i<n-1;i++){
           create[i][0]=in.nextInt();
           create[i][1]=in.nextInt();
        }
        int k=in.nextInt();
        List<Integer>res=new LinkedList<>();
        res.add(h);
        for(int i=0;i<n-1;i++){
            res.add(res.indexOf(create[i][1])+1,create[i][0]);
        }
        res.remove(res.indexOf(k));
        for(Integer num:res){
            System.out.print(num+" ");
        }
    }
}

发表于 2025-04-08 20:34:20 回复(0)
自己整了链表类自测没问题,提交就错,不给看全用例值,不知道错哪了。
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n=in.nextInt();
        int h=in.nextInt();
        ListNode<Integer> list=new ListNode<>(h);
        for(int i=0;i<n-1;i++){
            int val1=in.nextInt();
            int val2=in.nextInt();
            list.insertNode(val1,val2);
        }
        int k=in.nextInt();
        list.delNode(k);
        list.printNode();
        in.close();
    }
    public static class Node<T>{
        private T value;
        private Node<T> next;
        public Node(T value,Node<T> next){
            this.value=value;
            this.next=next;
        }
         public T getvalue(){
            return this.value;
        }
        public Node getNext(){
            return this.next;
        }
    }
    public static class ListNode<T>{
        private int N;
        Node<T> head;
        public ListNode(T value){
            head=new Node<>(value,null);
            N=1;
        }
        //判断链表是否为空
        public boolean isEmpty(){
            return N==0;
        }
        //插入节点
        public void insertNode(T val1,T val2){
            Node<T> n=head;
            //保证a输入前不存在于链表
            delNode(val1);
            while(n!=null){
                if(n.value==val2){
                    n.next=new Node<T>(val1,n.next);
                    N++;
                    return;
                }else{
                    n=n.next;
                }
            }
            //如果没找到b,就把b放到链表最后,并且增加a值
            n=new Node<T>(val2,null);
            n.next=new Node<T>(val1,null);
        }
        //删除节点
        public void delNode(T val3){
            if(isEmpty()){
                return;
            }
            while(head.value==val3){
                head=head.next;
                N--;
                if(N==0){
                    return;
                }
            }
            Node<T> n=head;
            while(n.next!=null){
                if(n.next.value==val3){
                    n.next=n.next.next;
                    N--;
                    if(N==0){
                        return;
                    }
                }else{
                    n=n.next;
                }
            }
        }
        //打印节点
        public void printNode(){
            if(isEmpty()){
                return;
            }
            Node<T> n=head;
            while(n!=null){
                System.out.print(n.value+" ");
                n=n.next;
            }
        }
    }
}


发表于 2025-03-23 20:13:46 回复(0)
list.add(list.indexOf(b) + 1, a);

list.remove(list.indexOf(k));
使用 List 插入、删除即可 
发表于 2025-01-27 20:15:00 回复(0)
import java.util.*;
// 1 输入链表结点个数
// 2 输入头结点的值
// 3 按照格式插入各个结点
// 4 输入要删除的结点的值
// 5 2 3 2 4 3 5 2 1 4 3
// 2 5 4 1
// 形成的链表为2->5->3->4->1 删掉节点3,返回的就是2->5->4->1

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String[] s = in.nextLine().split(" ");
            int[] arr = new int[s.length];
            for (int i = 0; i < s.length; i++) {
                arr[i] = Integer.parseInt(s[i]);
            }
            // 节点
            LinkedList<Integer> l = getIntegers(arr);
            for (Integer i : l) {
                System.out.print(i + " ");
            }
        }
    }

    private static LinkedList<Integer> getIntegers(int[] arr) {
        int num = arr[0];
        // 头
        int head = arr[1];
        // 删除
        int delete = arr[arr.length - 1];
        // 链表
        LinkedList<Integer> l = new LinkedList<>();
        l.add(head);
        for (int i = 2; i <= (num - 1) * 2; i += 2) {
            int pre = arr[i + 1];
            int next = arr[i];
            int index = l.indexOf(pre);
            l.add(index + 1, next);
        }
        // 需要删除的是值 如果不加(Integer)删除的是索引位置
        l.remove((Integer)delete);
        return l;
    }
}
发表于 2024-09-15 19:47:08 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            String[] strArr = s.split(" ");
            int[] arr = new int[strArr.length];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = Integer.parseInt(strArr[i]);
            }
            int num = arr[0];//节点数
            int head =  arr[1];//头元素
            int del = arr[arr.length - 1];//要删除的元素
            LinkedList<Integer> list = new LinkedList<>();
            list.add(head);
            //6 2        1 2 3 2 5 1 4 5 7 2            2
            for (int i = 2; i <= (num - 1) * 2; i += 2) {
                int pre = arr[i + 1];
                int next = arr[i];
                int index = list.indexOf(pre);
                list.add(index + 1, next);
            }
            //删除节点
            list.remove((Integer) del);
            list.forEach(o -> System.out.print(o + " "));
        }
    }
}

发表于 2024-07-06 17:50:24 回复(0)
看你们好多人都说样例错了?问题应该不大吧
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int nodes = in.nextInt();
        LinkedNode head = new LinkedNode(in.nextInt());
        for (int i = 1; i < nodes; i++) {
            int data = in.nextInt();
            int pre = in.nextInt();
            LinkedNode current = head;
            while (current.data != pre) {
                current = current.next;
            }
            current.next = new LinkedNode(data, current.next);
        }
        int toRemove = in.nextInt();
        if(head.data == toRemove) {
            head = head.next;
        } else {
            LinkedNode current = head;
            while (current.next.data != toRemove) {
                current = current.next;
            }
            current.next = current.next.next;
        }
        StringBuilder sb = new StringBuilder();
        LinkedNode current = head;
        while (current != null) {
            sb.append(current.data).append(" ");
            current = current.next;
        }
        System.out.println(sb.toString().trim());
    }
}

class LinkedNode {
    int data;
    LinkedNode next;
    LinkedNode(int data) {
        this.data = data;
        this.next = null;
    }
    LinkedNode(int data, LinkedNode next) {
        this.data = data;
        this.next = next;
    }
    boolean hasNext() {
        return this.next != null;
    }
    boolean isLast() {
        return this.next == null;
    }

}


发表于 2024-06-23 19:16:24 回复(0)
// 万恶的牛客输入输出
import java.util.*;

class ListNode{
    int val;
    ListNode next;
    ListNode(int val){
        this.val = val;
        next = null;
    }
    ListNode(int val, ListNode next){
        this.val = val;
        this.next = next;
    }
}

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void insert(int n, int m, ListNode head){
        ListNode p = head;
        while(p.val != m){
            p = p.next;
        }
        ListNode node = new ListNode(n, p.next);
        p.next = node;
    }

    public static void delete(int val, ListNode head){
        ListNode dummy = new ListNode(-1, head);
        ListNode p = dummy;
        while (p.next != null && p.next.val != val) {
            p = p.next;
        }
        if(p.next != null){
            p.next = p.next.next;
        }
        head = dummy.next;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int length = in.nextInt();
        int value = in.nextInt();
        ListNode head = new ListNode(value);

        for(int i = 1; i < length; i++){
            int n = in.nextInt();
            int m = in.nextInt();
            insert(n, m, head);
        }
       
        value = in.nextInt();
        delete(value, head);
        ListNode p = head;
        while (p != null) {
            System.out.print(p.val + " ");
            p = p.next;
        }
        System.out.println();

    }
}
发表于 2024-04-02 16:39:25 回复(0)
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            int b = in.nextInt();
            int[] arr =new int[2*a-2];
            for(int i=0;i<arr.length;i++){
                arr[i]=in.nextInt();
            }
            int delete = in.nextInt();
            //System.out.println(arr[7]);
            LinkedList<Integer> list = new LinkedList<>();
            list.add(b);
            for(int i=0;i<(a-1)*2;i=i+2){
                int one = arr[i];
                int two = arr[i+1];
                list.add(list.indexOf(arr[i+1])+1,arr[i]);
            }
            list.remove(list.indexOf(delete));
            for (Integer i : list) {
                System.out.print(i + " ");
            }
        }
       
    }
编辑于 2024-03-14 20:39:18 回复(0)
import java.util.*;

// 注意类名必须为 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 s = in.nextLine();
            String[] arr = s.split(" ");
            int n = Integer.valueOf(arr[0]);//子链数量
            int head =  Integer.valueOf(arr[1]);//头元素
            int delete = Integer.valueOf(arr[arr.length - 1]);//要删除的元素

            LinkedList<Integer> list= new LinkedList<Integer>();
            list.add(head);
            for (int i = 0; i < (n - 1) * 2; i+=2) {
                int one =  Integer.valueOf(arr[i+2]);//获取要插入的第一个元素
                int two =  Integer.valueOf(arr[i+3]);//获取要插入的第二个元素
                int index = list.indexOf(two);//获取要插入的第二个元素索引
                list.add(index+1,one);//从第二个元素索引尾插
            }

            list.remove(list.indexOf(delete));//删除要删除的元素
            for (Integer i : list) {
                System.out.print(i + " ");
            }
        }
    }
}

发表于 2024-01-25 16:38:06 回复(0)
import java.util.Scanner;

class Node {
    private Node next;
    private int value;
    public Node(int value) {
        this.value = value;
    }
    public int getValue() {
        return this.value;
    }
    public Node getNext() {
        return this.next;
    }
    public void setNext(Node next) {
        this.next = next;
    }
}

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String inputStr = in.nextLine();
        String[] strArr = inputStr.split(" ");
        int length = Integer.parseInt(strArr[0]);
        if (length > 1) {
            int headValue = Integer.parseInt(strArr[1]);
            int secondValue = Integer.parseInt(strArr[2]);
            Node second = new Node(secondValue);
            Node head = new Node(headValue);
            head.setNext(second);
            Node current = head;
            Node pre;
            for (int i = 4; i < strArr.length - 2; i = i + 2) {
                int value = Integer.parseInt(strArr[i]);
                int afValue = Integer.parseInt(strArr[i + 1]);
                Node newNode = new Node(value);
                current = head;
                while (current != null) {
                    if (afValue == current.getValue()) {
                        newNode.setNext(current.getNext());
                        current.setNext(newNode);
                        break;
                    }
                    current = current.getNext();
                }
            }
            /*
            current = head;
            while(current!=null){
                System.out.print(current.getValue()+" ");
                    current = current.getNext();
            }
            System.out.println();
            */
            Node delNode = new Node(Integer.parseInt(strArr[strArr.length - 1]));
            current = head;
            pre = head;
            while (current != null) {
                if (current.getValue() == delNode.getValue()) {
                    if (current.equals(head)) {
                        head = current.getNext();
                    }
                    pre.setNext(current.getNext());
                }
                pre = current;
                current = current.getNext();
            }
            current = head;
            while (current != null) {
                System.out.print(current.getValue() + " ");
                current = current.getNext();
            }
            System.out.println();
        } else {
            if (strArr[1].equals(strArr[2])) {
                System.out.println();
            } else {
                System.out.println(strArr[1]);
            }
        }
    }
}

编辑于 2024-01-03 16:45:53 回复(0)
这题需要不需要考虑换位置的情况,比如样例5 2 1 4 3 2 4 3 5 2 3,得出的结果是2541,但是如果是5 2 1 4 3 2 4 3 5 2 3这样呢,结果是不是要跟前面的一样
发表于 2023-12-17 12:00:57 回复(0)
反正最后只检验输出结果对不对,我们直接定义一个数组,存入每个节点值,然后输出的时候,在结果里面跳过这个值就行了!哈哈哈哈,如果这是在力扣,人家就直接要求返回链表的头指针。开个玩笑咯,还是要认真写:
import java.util.Scanner;

public class T47 {
    public static void main(String[] args) {
        class ListNode {
            int value;
            ListNode next;

            ListNode(int x) {
                this.value = x;
            }
        }
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            String[] split = s.split(" ");
            int number = Integer.parseInt(split[0]);
            //默认在创建链表过程中,头节点不会改变
            int headValue = Integer.parseInt(split[1]);
            int delete = Integer.parseInt(split[split.length - 1]);
            ListNode head = new ListNode(headValue);
            //构建链表
            for (int i = 0; i < number - 1; i++) {
                int index = 2 + i * 2;
                int firstValue = Integer.parseInt(split[index]);
                int secondValue = Integer.parseInt(split[index + 1]);
                ListNode temp = head;
                while (true) {
                    if (temp.value == secondValue) {
                        if (temp.next == null) {
                            ListNode listNode = new ListNode(firstValue);
                            temp.next = listNode;
                            break;
                        } else {
                            ListNode listNode = new ListNode(firstValue);
                            listNode.next = temp.next;
                            temp.next = listNode;
                            break;
                        }
                    } else {
                        temp = temp.next;
                    }
                }
            }
            //删除指定元素对应的节点
            if (head.value == delete) {
                head = head.next;
            } else {
                ListNode temp = head;
                while (true) {
                    if (temp.next.value == delete) {
                        if (temp.next.next == null) {
                            temp.next = null;
                            break;
                        } else {
                            temp.next = temp.next.next;
                            break;
                        }
                    } else {
                        if (temp.next == null) {
                            break;
                        } else {
                            temp = temp.next;
                        }
                    }
                }
            }
            ListNode temp = head;
            String result = "";
            //节点全部被删除的情况
            if (temp == null) {
                System.out.println("");
                return;
            }
            //有节点的情况下,将所有value值拼接上去
            while (true) {
                result += temp.value + " ";
                if (temp.next == null) {
                    break;
                } else {
                    temp = temp.next;
                }
            }
            System.out.println(result);
        }
    }
}



发表于 2023-11-28 18:16:09 回复(0)