题解 | #【模板】链表#
【模板】链表
http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
import java.math.*;
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.*;
public class Main {
static FastReader sc = new FastReader();
static void solve01() {
// FastReader sc = new FastReader();
int t = Integer.parseInt(sc.nextLine());
MyLinkedList ll = new MyLinkedList();
while (t-- > 0) {
String arr[] = sc.nextLine().split(" ");
switch(arr[0]) {
case "insert":
ll.insert(arr[1], arr[2]);
break;
case "delete":
ll.delete(arr[1]);
break;
}
// if (arr[0].equals("insert")) {
// ll.insert(arr[1], arr[2]);
// }
// else if (arr[0].equals("delete")) {
// ll.delete(arr[1]);
// }
}
ll.show();
}
public static void main(String[] args) {
solve01();
}
//输出
static PrintWriter out;
//输入类
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {return new BigInteger(next());}
BigDecimal nextBigDecimal() {return new BigDecimal(next());}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
class MyLinkedList {
private Node head;
private int length;
public MyLinkedList() {
head = new Node(null);
length = 0;
}
public boolean isEmpty() {
return length == 0;
}
public void insert(String x, String y) {
Node cur = head;
Node insertNode = new Node(y);
while (cur.next != null) {
if (cur.next.data.equals(x)) {
insertNode.next = cur.next;
cur.next = insertNode;
length++;
return;
}
cur = cur.next;
}
insertNode.next = cur.next;
cur.next = insertNode;
length++;
}
public void delete(String x) {
Node cur = head;
while (cur.next != null) {
if (cur.next.data.equals(x)) {
cur.next = cur.next.next;
length--;
return;
}
cur = cur.next;
}
}
public void show() {
if (isEmpty()) {
System.out.println("NULL");
return;
}
Node cur = head.next;
for (int i = 0; i < length - 1; i++) {
System.out.print(cur.data + " ");
cur = cur.next;
}
System.out.println(cur.data);
}
}
class Node {
String data;
Node next;
public Node() {}
public Node(String data) { this.data = data; }
}