【华为OJ】【093-从单向链表中删除指定值的节点】

【华为OJ】【算法总篇章】

【华为OJ】【093-从单向链表中删除指定值的节点】

【工程下载】

题目描述

输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
链表结点定义如下:
struct ListNode
{
      int       m_nKey;
      ListNode* m_pNext;
};
详细描述:
本题为考察链表的插入和删除知识。
链表的值不能重复
构造过程,例如
1 -> 2
3 -> 2
5 -> 1
4 -> 5
7 -> 2
最后的链表的顺序为 2 7 3 1 5 4
删除 结点 2
则结果为 7 3 1 5 4

输入描述:

1 输入链表结点个数
2 输入头结点的值
3 按照格式插入各个结点
4 输入要删除的结点的值

输出描述:

输出删除结点后的序列

输入例子:

5
2
3 2
4 3
5 2
1 4
3

输出例子:

2 1 5 4

算法实现

import java.util.List;
import java.util.Scanner;

/** * Author: 王俊超 * Date: 2016-05-03 09:47 * CSDN: http://blog.csdn.net/derrantcm * Github: https://github.com/Wang-Jun-Chao * Declaration: All Rights Reserved !!! */
public class Main {
    private static class ListNode {
        int key;
        ListNode next;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNextLong()) {
            int num = scanner.nextInt();
            int h = scanner.nextInt();
            ListNode head = new ListNode();
            head.key = h;

            for (int i = 0; i < num - 1; i++) {
                int newVal = scanner.nextInt();
                int afterVal = scanner.nextInt();
                addNode(newVal, afterVal, head);
            }

            int del = scanner.nextInt();

            head = delete(del, head);
            System.out.println(getString(head));

        }
        scanner.close();
    }

    private static String getString(ListNode head) {
        StringBuilder builder = new StringBuilder();

        while (head!= null) {
            builder.append(head.key).append(' ');
            head = head.next;
        }

// return builder.substring(0, builder.length() - 1);
        return builder.toString();
    }

    private static void addNode(int newVal, int afterVal, ListNode head) {
        ListNode n = head;
        while (n != null) {
            if (n.key == afterVal) {
                ListNode node = new ListNode();
                node.key = newVal;
                node.next = n.next;
                n.next = node;
                break;
            }
            n = n.next;
        }
    }

    private static ListNode delete(int val, ListNode head) {
        if (head.key == val) {
            ListNode ret = head.next;
            head.next = null;
            return ret;
        } else {
            ListNode prev = head;
            while (prev.next != null) {
                if (prev.next.key == val) {
                    prev.next = prev.next.next;
                    break;
                }
                prev = prev.next;
            }

            return head;
        }
    }
}

你可能感兴趣的:(java,算法,链表,华为)