【题目】 分别实现反转单向链表和反转双向链表的函数。
【要求】 如果链表长度为N,时间复杂度要求为O(N),额外空间 复杂度要求为O(1)
我不是计算机系的,对这方面知识也不是很清楚,我记得当时这个反转我扣了一个上午,当时心情也比较烦,
后来一个上午就扣懂了这个题目,后来我学习了数据结构跟算法的后面课程
回过头写博客整理的时候,我只用了不到20分钟,就理解了,
因为脑海里有那种抽象思维
所以像我这样屌丝的人,都能弄懂,如果你看到这篇博客,放心,你也能弄懂
package basic_class_03;
/**
* 反转单向和双向链表
* 【题目】 分别实现反转单向链表和反转双向链表的函数。
* 【要求】 如果链表长度为N,时间复杂度要求为O(N),额外空间 复杂度要求为O(1)
*
* 注意反转链表一定要有抽象思维 都是教科书上的知识
* 如果不太清楚的话,可以试着debug 等熟悉了之后
* 你再去试着用抽象去接理解单向跟双向链表的反转
* 重要的是那种抽象思维
*
* @author lenovo
*
*/
public class Code_07_ReverseList {
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
public static Node reverseList(Node head) {
Node pre = null;
Node next = null;
while(head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static Node reverseList_1(Node head) {
Node pre = null;
Node next = null;
while(head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static Node reverseList_2(Node head) {
Node pre = null;
Node next = null;
while(head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static class DoubleNode {
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
this.value = data;
}
}
/**
* 脑子里一定要有那种抽象思维
* @param head
* @return
*/
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while(head != null) {
next = head.next;
head.last = next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void printLinkedList(Node head) {
System.out.println("Linked List: ");
while(head != null) {
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
printLinkedList(head1);
head1 = reverseList(head1);
printLinkedList(head1);
}
}