手动输入链表并给出需要移除的链表元素,打印经历移除之后的新链表

import java.util.Scanner;

public class demo {
    public static void main(String[] args) {
        //移除链表元素
        //构造链表1-->4-->2-->4
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();//链表共有节点个数
        sc.nextLine();

        //构造单链表  尾插法
        ListNode head = null;//head一旦确定,就不再移动
        ListNode tail = null;//随着新节点的加入,不断向后移动
        if (n > 0){
            for (int i = 1; i <= n; i++){
                int val = sc.nextInt();//输入链表
                ListNode newNode = new ListNode(val);
                if (head == null){//插入第一个节点时,head既是头又是尾
                    head = newNode;
                    tail = head;
                }
                else{
                    tail.next = newNode;
                    tail = tail.next;
                }
            }
        }
        sc.nextLine();

        int target = sc.nextInt();//需要移除的目标值

        //如果头节点本身就要删除
        while (head != null && head.val == target){
            head = head.next;//直接将head后移
        }
        //判断是否为空
        if (head == null){
            return;
        }
        //处理头节点之后的节点
        ListNode current = head;
        while (current.next != null){
            if (current.next.val == target){//找到目标,则移除
                current.next = current.next.next;
            }
            else {//没找到,继续向后
                current = current.next;
            }
        }
        while (head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
    }
}
class ListNode{
    int val;
    ListNode next;
    ListNode(int val){
        this.val = val;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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