【华为OJ】【093-从单向链表中删除指定值的节点】
2016-05-21 06:35
513 查看
【华为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; } } }
相关文章推荐
- Ps回调通知例程、Dpc定时器、内核线程使用方法.
- 【华为OJ】【092-学英语】
- 一个PsSetLoadImageNotifyRoutine回调内核注入DLL,支持xp ~ win7源码
- 文件上传小技巧/原生态【html篇】
- LeetCode 52. N-Queens II(N皇后)
- 如何在Windows 7平台搭建Android Cocos2d-x3.2alpha0开发环境(官方)
- 【华为OJ】【091-数据分类处理】
- Apache Ant安装与配置
- 登堂入室
- LeetCode 51. N-Queens(N皇后)
- LeetCode 50. Pow(x, n)(求幂)
- 源码推荐(0521):弹幕,超炫的点赞动画,网易新闻
- 十天冲刺开发第三天个人工作总结
- 得到汉字拼音首字母
- LeetCode 49. Group Anagrams(分组同构异形词)
- 计算机程序的构造和解释 练习 1.31
- 国家明确规划重点软件和集成电路设计领域
- leetcode %15 in cpp
- 粘性动画以及果冻效果的实现
- 小酌重构系列[20]——用条件判断代替异常