单向链表
c++
在这里插入代码片
Java
package 数据结构与算法;
import java.util.*;
public class 链表 {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
n1.append(n2).append(n3).append(new Node(4));
n1.show();
Node n5 = new Node(5);
n1.after(n5);
n1.show();
}
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
public Node append(Node node) {
Node currentNode = this;
while (true) {
Node nextNode = currentNode.next;
if (nextNode == null) break;
currentNode = nextNode;
}
currentNode.next = node;
return this;
}
public void show() {
Node currentNode = this;
while(true) {
System.out.println(currentNode.data + " ");
currentNode = currentNode.next;
if (currentNode == null) break;
}
}
public void removeNext() {
Node newNext = next.next;
this.next = newNext;
}
public void after(Node node) {
Node nextNext = next;
this.next = node;
node.next = nextNext;
}
public Node next() {
return this.next;
}
public int getData() {
return this.data;
}
public boolean isLast() {
return next == null;
}
}
双向链表:
c++
Java
package 数据结构与算法;
public class 链表_双向 {
public static void main(String[] args) {
DoubleNode n1 = new DoubleNode(1);
DoubleNode n2 = new DoubleNode(2);
DoubleNode n3 = new DoubleNode(3);
n1.after(n2);
n2.after(n3);
System.out.println(n2.pre().getData());
System.out.println(n2.getData());
System.out.println(n2.next().getData());
n1.show();
}
}
class DoubleNode {
private int data;
private DoubleNode next = this;
private DoubleNode pre = this;
public DoubleNode() {
}
public DoubleNode(int data) {
this.data = data;
}
public void show() {
DoubleNode currentNode = this;
while (true) {
System.out.println(currentNode.data + " ");
currentNode = currentNode.next;
if (currentNode == null) {
break;
}
}
}
public void after(DoubleNode node) {
DoubleNode nextNext = next;
this.next = node;
node.pre = this;
node.next = nextNext;
nextNext.pre = node;
}
public DoubleNode next() {
return this.next;
}
public DoubleNode pre() {
return this.pre;
}
public int getData() {
return this.data;
}
}