题解 | #【模板】链表#
【模板】链表
http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
sc.nextLine();
MyList myList = new MyList();
while(sc.hasNextLine()){
String input = sc.nextLine().trim();
if(input.equals(""))
continue;
String[] arr = input.split(" ");
if(arr[0].equals("insert"))
myList.insert(Integer.valueOf(arr[1]),Integer.valueOf(arr[2]));
else if(arr[0].equals("delete"))
myList.delete(Integer.valueOf(arr[1]));
}
System.out.println(myList);
}
}
class Node{
int val;
Node next;
public Node(int val){
this.val = val;
}
}
class MyList {
// Node root=new Node(-1);
Node root;
public MyList() {
root = new Node(-1);
}
public void insert(int x, int y) {
Node xPre = findPre(x);
Node yNode = new Node(y);
yNode.next = xPre.next;
xPre.next = yNode;
}
public void delete(int x) {
Node xPre = findPre(x);
if (xPre.next != null) {
xPre.next = xPre.next.next;
}
}
public Node findPre(int x) {//查找节点,如果不存在返回尾节点
Node cur = root;
while (cur.next != null && cur.next.val != x) {
cur = cur.next;
}
return cur;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (root.next == null)
return "NULL";
else {
Node cur = root.next;
while (cur != null) {
sb.append(cur.val + " ");
cur = cur.next;
}
return sb.toString();
}
}
}
注意:
1.在java中使用class代替了c++的结构体
2.链表可以通过消耗一个变量空间,用来作链表的头结点,方便代码的书写,即使是空链表的插入操作也与其他链表相同。
3.在java中System.out.println()输出Object对象时,会默认调用其toString(),我们可以通过重写toString()修改为自己想要的输出。具体原理如下:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}