例如有一单向链表
54->30->37->61->1->60->25->76->60->95
原链表头节点54,尾节点:95
实现效果:
95->60->76->25->60->1->61->37->30->54
新链表头节点95,尾节点54
实现原理:
从头节点开始遍历整个链表,对每个节点指向的前后节点引用进行交换,最后设置头节点和尾节点
Java类:
Node.java
节点对象,包含节点本身属性及方法
NodeList.java
链表操作类,记录链表头节点和尾节点,操作链表例如链表追加,链表反转等方法
TestNode.java
测试类
实现代码:
package demo;
/**
* 节点实体类
* @author sunlh
*
*/
public class Node {
private Node pre;// 上一个节点
private Node next;// 下一个节点
private int data;// 数据
public Node(int data) {
this.data = data;
}
public void append(Node node) {
if (this.next == null) {
this.next = node;
node.pre = this;
} else {
this.next.append(node);
}
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void setData(int data) {
this.data = data;
}
public boolean hasPre() {
return this.pre != null;
}
public boolean hasNext() {
return this.next != null;
}
public int getData() {
return data;
}
}
package demo;
public class NodeList {
Node head;
Node last;
/**
* 追加
* @param node
*/
public void append(Node node) {
if (head.getNext() == null) {
head.setNext(node);
node.setPre(head);
} else {
head.getNext().append(node);
}
}
/**
* 遍历
*/
public String toString() {
Node curr = head;
StringBuilder sBuilder = new StringBuilder();
while (curr != null) {
sBuilder.append(curr.getData()).append(curr.hasNext() ? "->" : "");
curr = curr.getNext();
}
return sBuilder.toString();
}
/**
* 倒置反转
*/
public String reverse() {
Node curr = head;
Node newHead = null;
Node newLast = null;
while (curr != null) {
Node pre = curr.getPre();
Node next = curr.getNext();
if (pre == null) newLast = curr; // 前一个节点为空,作为新的尾节点
if (next == null) newHead = curr;// 后一个节点为空,作为新的头节点
curr.setNext(pre);// 当前节点的下一个节点作为当前节点的上一个节点
curr.setPre(next);// 当前节点的上一个节点作为当前节点的下一个节点
curr = curr.getPre();// 继续处理原链表节点的下一个节点
}
head = newHead;// 设置头节点
last = newLast;// 设置尾节点
return this.toString();
}
}
package demo;
public class TestNode {
public static void main(String[] args) throws InterruptedException {
NodeList list = new NodeList();
System.out.println("构造长度为10的双向链表");
for (int i = 0; i < 10; i++) {
int r = (int)(Math.random() * 100);
Node node = new Node(r);
if (i == 0) {
list.head = node;// 头节点
} else {
list.head.append(node);
}
list.last = node;// 尾节点
}
// 遍历
System.out.println(list.toString());
// 倒置反转
System.out.println(list.reverse());
}
}
结果输出:
构造长度为10的双向链表
38->74->40->81->77->34->91->93->92->0
0->92->93->91->34->77->81->40->74->38