/**
* 问题:反转双向链表
*
* 要求:
* 如果链表长度为 N,时间复杂度为O(N),额外的空间复杂度为O(1)。
*
* @author 雪瞳
*
*/
public class Node<T>{
public T value;
public Node next;
public Node last;
public Node(T data){
this.value =data;
}
}
public class reverseList {
private Node current = null;
private Node currentNext = null;
public Node reverse(Node head) {
///记录current的节点是head的下一个节点。
current = head.next;
//切断 head.next指向current
//头节点变尾结点 head的下一个设为空
head.next = null;
while(current != null) {
//记录currentNext的节点是current的下一个节点。
currentNext = current.next;
//current是当前节点
//将当前节点的下一节点重新更改指向,第一次也就是之前被截断的 head头节点
current.next = head;
current.last = currentNext;
//将头节点和当前节点重新赋值
head = current;
current = currentNext;
}
return head;
}
}
import java.util.Random;
import java.util.Scanner;
public class testReverseList {
public static void main(String[] args) {
reverseList reverse = new reverseList();
testReverseList test = new testReverseList();
Random rand = new Random();
Scanner sc = new Scanner(System.in);
System.out.println("请输入链表长度");
int K = sc.nextInt();
Node nodes[]=new Node[K];
for(int i=0;i<nodes.length;i++) {
nodes[i]=new Node(rand.nextInt(20)+1);
}
for(int i =0;i<nodes.length-1;i++) {
nodes[i].next=nodes[i+1];
}
Node head = nodes[0];
//test
test.showNode(head);
Node reverseNode = reverse.reverse(head);
test.showNode(reverseNode);
}
public void showNode(Node head) {
System.out.println("链表内的元素如下所示...");
while(head != null) {
System.out.print(head.value+" ");
head = head.next;
}
System.out.println();
}
}