今天主要编写了链表,其具体代码如下:
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class LinkList {
private Node head;
public LinkList() {
// TODO Auto-generated constructor stub
head = new Node("");
}
public void Insert() {
String string;
Node node = head;
while (!(string = StdIn.readString()).equals("#")) {
Insert(node, new Node(string));
node = node.next;
}
}
/**
* insert node n2 after node n1
* @param n1
* @param n2
*/
public void Insert(Node n1, Node n2) {
if (n1 == null || n2 == null);
else {
Node n3 = n1.next;
n1.next = n2;
n2.next = n3;
}
}
/**
* delete the k-th node
* @author Bjy_PC
*
*/
public String delete(int k) {
if (head.next == null) return null;
Node node = head;
int count = 0;
String string = new String();
while (node.next != null) {
if (k - 1 == count) {
string = node.next.value;
node.next = node.next.next;
break;
}
node = node.next;
count++;
}
return string;
}
/**
* find the max element using recursion
* @author Bjy_PC
*
*/
public Node max() {
return max(head.next, head.next.next);
}
public Node max(Node n1, Node n2) {
if (n2.next == null) return n1;
else return max(n1.value.compareTo(n2.value) >= 0? n1:n2, n2.next);
}
/**
* show the list
* @author Bjy_PC
*
*/
@Override
public String toString() {
// TODO Auto-generated method stub
Node node = head;
String string = new String("");
while (node.next != null) {
node = node.next;
string += node.value + "--->";
}
return string;
}
/**
* reverse the linklist
* @author Bjy_PC
*
*/
public Node reverse() {
Node first = head.next;
Node second = first.next;
Node reverse = null;
if (first == null || second == null) return this.head.next;
else {
while (first != null) {
first.next = reverse;
reverse = first;
first = second;
if (second != null)
second = second.next;
}
}
head.next = reverse;
return reverse;
}
class Node {
Node next;
String value;
public Node(String item) {
// TODO Auto-generated constructor stub
this.value = item;
this.next = null;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkList list = new LinkList();
list.Insert();
StdOut.println(list);
list.delete(1);
list.Insert(list.head.next.next, list.new Node("perfect"));
StdOut.println(list);
StdOut.println("max value :" + list.max().value);
list.reverse();
StdOut.println(list);
}
}
其中每个操作的时间复杂度最多为线性的,对空间复杂度来说,Node节点占用72字节,其中Node对象开销16个字节,内部类占用8字节的额外开销,指向Node的引用占用8个字节,String对象占用40个字节。则长度为N的链表至少需要24 + 72*N个字节(不包括字符串数组的字节数),其中LinkList对象有16个字节的对象开销,head节点的引用占用8个字节。