OJ-------从单向链表中删除指定节点
2017-02-24 14:56
387 查看
题目描述
输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。 链表结点定义如下: 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 ////正确结果应该是 2 4 5 1
算法实现
import java.util.List;import java.util.Scanner;
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;
}
}
}
相关文章推荐
- 华为OJ——从单向链表中删除指定值的节点
- 华为OJ:从单向链表中删除指定值的节点
- 华为OJ从单向链表中删除指定值的节点
- 华为OJ(从单向链表中删除指定值的节点)
- 【华为OJ】【093-从单向链表中删除指定值的节点】
- 华为oj中级 从单向链表删除指定节点
- 从单向链表中删除指定值的节点(OJ 不用看这题)
- 华为OJ——从单向链表中删除指定值的节点
- 删除单向链表的指定节点
- 华为机试:从单向链表中删除指定值的节点
- 从单向链表中删除指定值的节点
- 24.从单向链表中删除指定值的节点
- 从单向链表中删除指定值的节点
- 单向链表(二) 删除指定位置的节点
- 数据结构之链表面试题汇总(四)得到两个单链表相交的第一个交点、用O(1)的时间效率删除单向链表中的指定节点
- 从单向链表中删除指定值的节点
- 从单向链表中删除指定值的节点(格式控制真坑,末尾要打印空格,样例输出有错误)
- [编程题]从单向链表中删除指定值的节点
- 单向链表删除节点
- 删除单向链表中重复的节点