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

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

http://www.nowcoder.com/questionTerminal/f96cd47e812842269058d483a11ced4f

没什么难点,删除单链表节点是lc的简单题,主要是大家在输出完一个用例后,一定记得换行!!我活活找了快一个小时的bug,结果发现是这。。ACM模式太坑了。。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int num =in.nextInt();
            Node head = new Node(in.nextInt());
            num--;
            while(num > 0){
                int cur = in.nextInt();
                int pre = in.nextInt();
                insert(head,pre,cur);
                num--;
            }
            int deleteVal = in.nextInt();
            //删除头节点
            if(head.val == deleteVal){
                head = head.next;
            }
            else{
                delete(head,deleteVal);
            }

            Node test = head;
            //打印输出
            while(test != null){
                System.out.print(test.val + " ");
                test = test.next;
            }
            //千万别忘了换行!!!!!!
            System.out.println();
        }
    }
    //插入Node
    public static void insert(Node head, int preVal, int newVal){
        Node newNode = new Node(newVal);
        Node cur = head;
        Node temp;
        while(cur != null){
            if(cur.val == preVal){
                temp = cur.next;
                cur.next = newNode;
                newNode.next = temp;
                return;
            }
            cur = cur.next;
        }
    }

    //删除Node
    public static void delete(Node head, int delete){
        Node cur = head;
        Node temp;
        while(cur.next != null){
            if(cur.next.val == delete){
                cur.next = cur.next.next;
                return;
            }
            cur = cur.next;
        }
    }
}
class Node{
    int val;
    Node next;
    Node(int val){
        this.val = val;
    }
}
全部评论

相关推荐

小鹏、大疆、米哈游、MinMax小鹏上午投的下午就约面,进度未免也太快了
蛇年行大运fff:哥们 盗贴有意思吗,我发xhs上的给你搬过来了😅😅😅
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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