题解 | #【模板】链表#
【模板】链表
http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
import java.util.Scanner;
class MyLinkedList {
static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
};
//带头链表
private ListNode head;
//打印链表
public void display() {
ListNode cur = head;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
if (head == null) {
System.out.println("NULL");
}
}
//尾插
public void addLast(int val) {
ListNode node = new ListNode(val);
if (head == null) {
head = node;
return;
}
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
//在指定x位置插入
public void insert(int key, int val) {
ListNode node = new ListNode(val);
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
pre.next = head;
ListNode next = pre.next;
while (next != null ) {
if (next.val == key) {
node.next = next;
pre.next = node;
head = dummy.next;
return;
}
pre = pre.next;
next = next.next;
}
addLast(val);
}
//删除第一次出现的key值
public void delete(int key) {
if (head != null && head.val == key) {
head = head.next;
return;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode pre = dummyHead;
ListNode cur = pre.next;
while (cur != null) {
if (cur.val == key) {
pre.next = cur.next;
return;
}
pre = pre.next;
cur = cur.next;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
MyLinkedList list = new MyLinkedList();
for (int i = 0; i < n; i++) {
String[] data = in.nextLine().split(" ");
switch(data[0]) {
case "insert":
list.insert(Integer.parseInt(data[1]),Integer.parseInt(data[2]));
break;
case "delete":
list.delete(Integer.parseInt(data[1]));
break;
}
}
list.display();
in.close();
}
}