题目
实现反转单向链表和双向链表,要求:如果链表长度为N,时间复杂度为O(N),额外空间复杂度为O(1)
参考答案
图形表示
单向链表
单向反转请参考
双向链表
反转前:头节点的前驱是null,尾节点的后继是null。
反转后:以前的头节点的后继是null,以前的尾节点的前驱是null
java代码实现如下:
//双向链表节点
public class DoubleNode {
public int value;
//前驱
public DoubleNode pre;
//后继
public DoubleNode next;
public DoubleNode(int value) {
this.value = value;
}
}
public class DoubleNodeReversal {
public static void main(String[] args) {
DoubleNode head = new DoubleNode(1);
//构建一个双向链表1 2 3 4
DoubleNode mid1 = new DoubleNode(2);
DoubleNode mid2 = new DoubleNode(3);
DoubleNode tail = new DoubleNode(4);
head.next = mid1;
mid1.next = mid2;
mid2.next = tail;
System.out.println("反转前");
print(head);
head = reversalList(head);
System.out.println("反转后");
print(head);
}
//把自己的前驱变后继,把后继变前驱
private static DoubleNode reversalList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next;
while (head != null) {
next = head.next;
head.next = pre;
head.pre = next;
pre = head;
head = next;
}
System.out.println();
return pre;
}
//遍历打印节点信息
private static void print(DoubleNode head) {
while (head != null) {
System.out.print(head.value);
//优化打印日格式
System.out.print(" ");
head = head.next;
}
}
}
关键字
链表,单向,双向,反转
老规矩,代码截图,免得手机上看代码很不爽