之前上课学的都是用C++,在这里用java把常用的数据结构实现一遍,直接上代码:
public class LinkedList {
private Node first;
private Node last;
class Node {
int data;
String names;
Node next;
public Node(int data, String names) {
this.data = data;
this.names = names;
this.next = null;
}
}
public boolean isEmpty() {
return first==null;
}
public void print() {
Node current = first;
while (current!=null) {
System.out.println("current data: " + current.data);
current = current.next;
}
}
public void insertLast(int data, String names) {
Node node = new Node(data, names);
if(isEmpty()) {
first = node;
last = node;
} else {
last.next = node;
last = node;
}
}
public void insertFirst(int data, String names) {
Node node = new Node(data, names);
if(isEmpty()) {
first = node;
last = node;
} else {
node.next = first;
first = node;
}
}
public int delete(Node node) {
Node current = first;
Node tmp = first;
if(isEmpty()) {
//不存在
return -1;
} else {
if(first.data == node.data) {
first = first.next;
} else {
while (current!=null) {
if(current.data != node.data) {
tmp = current;
current = current.next;
} else {
tmp.next = current.next;
return 1;
}
}
}
}
//没有找到对应node
return 0;
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.insertLast(90, "zhangda");
ll.insertLast(80, "yuefei");
ll.print();
Node node = ll.new Node(80, "yuefei");
ll.delete(node);
System.out.println("------- 删除之后 ------- :");
ll.print();
}
}
运行结果:
再来看一下基于上个例子,如何实现链表倒序打印呢?
public class ReverseStuLinkedList extends LinkedList {
public void reverse_print() {
Node current = first;
Node before = null;
while (current != null) {
last = before;
before = current;
current = current.next;
before.next = last;
}
current = before;
while (current != null) {
System.out.println("current data is : " + current.data);
current = current.next;
}
}
public static void main(String[] args) {
ReverseStuLinkedList rsl = new ReverseStuLinkedList();
rsl.insertLast(90,"zhangda");
rsl.insertLast(80, "yuefei");
rsl.print();
System.out.println("逆转打印————");
rsl.reverse_print();
}
}
说一下如何遍历实现逆转的逻辑,相当于使用俩个辅助变量(before,last),每次last的位置就是before下一次的位置,然后当前before的下一位置就是last,以这个方法来依次推进遍历链表。(核心方法就是它,又学习到了)