要求:
链表长度N,时间复杂度为O(N),额外空间复杂度为O(1)。
思路总结:
用了四个辅助节点,pre, end, cur, next,代码比较繁杂,但是易于理解。
收获:
单链表->null。
null<-/->双链表->null。
//反转单双链表
package com.company;
public class Main {
public static class Node {
public int value;
public Node next;
public Node() { this.next = null; }; //初始化一个空链表
public Node(int value) { this.value = value; }
}
public static class DuLNode {
public int value;
public DuLNode next;
public DuLNode prior;
public DuLNode() { this.next = null; this.prior = null; }; //初始化一个空链表
public DuLNode(int value) { this.value = value; }
}
public static Node CreatNewLinkedList(Node head, int[] a) {
//System.out.print("List is: ");
Node r = head;
for (int i : a) {
Node p = new Node(i);
r.next = p;
p.next = null;
r = r.next;
//System.out.print(p.value + " ");
}
//r.next = null;
//System.out.println();
return head.next;
}//尾插法
public static DuLNode CreatNewDuLLinkedList(DuLNode head, int[] a) {
DuLNode r = head;
for (int i : a) {
DuLNode p = new DuLNode(i);
r.next = p;
//p.next = null;
p.prior = r;
r = r.next;
}
//r.next = null;
head.next.prior = null;
return head.next;
}//尾插法
public static Node ReverseLinkedList(Node node) {
Node pre = node;
Node cur = node.next;
Node next = node.next.next;
Node end = node;
while (next != null) {
end.next = next;
cur.next = pre;
pre = cur;
cur = next;
next = next.next;
if (next == null) {
end.next = null;
cur.next = pre;
pre = cur;
}
//System.out.println(1);
//node = null;
}
return pre;
}
public static DuLNode ReverseDuLLinkedList(DuLNode node) {
DuLNode pre = node;
DuLNode cur = node.next;
DuLNode next = node.next.next;
DuLNode end = node;
while (next != null) {
end.next = next;
next.prior = end;
cur.next = pre;
pre.prior = cur;
pre = cur;
cur = next;
next = next.next;
if (next == null) {
end.next = null;
cur.next = pre;
pre.prior = cur;
cur.prior = null;
pre = cur;
}
//System.out.println(1);
//node = null;
}
return pre;
}
public static void PrintLinkedList(Node node) {
System.out.print("List is: ");
while (node != null) {
System.out.print(node.value + " ");
node = node.next;
}
System.out.println();
}
public static void PrintLinkedList(DuLNode node) {
System.out.print("DuLList is: ");
DuLNode end = new DuLNode();
while (node != null) {
System.out.print(node.value + " ");
end = node;
node = node.next;
}
System.out.print("| ");
while (end != null) {
System.out.print(end.value + " ");
end = end.prior;
}
System.out.println();
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Node head = new Node();
DuLNode duLNode = new DuLNode();
head = CreatNewLinkedList(head, a);
PrintLinkedList(head);
head = ReverseLinkedList(head);
PrintLinkedList(head);
System.out.println("===================");
duLNode = CreatNewDuLLinkedList(duLNode, a);
//int aaa = 2;
//while (aaa-- != 0) {
PrintLinkedList(duLNode);
//}
duLNode = ReverseDuLLinkedList(duLNode);
PrintLinkedList(duLNode);
}
}