单链表与双链表
单链表:两个属性分别为值,和下一个节点的地址
双链表:三个属性分别为值,上一个节点的地址和下一个节点的地址
题目一:单链表的反转
public class reverseLinkedList {
public static class Node {
public int vaule;
public Node next;
public Node(int vaule) {
this.vaule = vaule;
}
}
static Node reverseLinkedList(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 void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
//如果仅像下面这样操作,head的vaule还是1,因为引用的传递,在上面的reverseLinkedList方法中如果在head = next;后面对head的属性进行操作,改变的实际是next的属性,因为head指向next
//reverseLinkedList(head);
//System.out.println(head.vaule);//head.vaule=1
head = reverseLinkedList(head);
System.out.println(head.vaule);
System.out.println(head.next.vaule);
System.out.println(head.next.next.vaule);
}
}
JVM的释放:在上面这种链表中,只有一个对象head,如果先改变了head的指向,而不改变head,原先head的所有指向都会消失,这叫做JVM的释放
题目二:双链表的反转
public class reverseDoubleList {
public static class Node {
public int vaule;
public Node next;
public Node last;
public Node(int vaule) {
this.vaule = vaule;
}
}
static Node reverseDoubleList(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
//记录下一个位置
next = head.next;