文章目录
反转单向链表
1.题目
实现反转单向链表的函数。
要求: 若链表的长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)。
2.算法思路
- 反转一个单向链表后形成了一个新的链表,记为newHead。
- 所以对原链表不断做头删,对新链表不断做头插即可。
- 当原链表被头删完(head=null),说明此时链表反转完成。
(1)单链表的头删
(2)单链表的头插
3.算法思路
public static void printLinkedList(Node head){
System.out.println("LinkedList:");
while(head != null){
System.out.println(head.value + " ");
head = head.next;
}
}
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;//pre结点右移
head=next;//head结点右移
}
return pre;
}
public static void main(String[] args){
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3); //定义一个单向链表1-2-3
printLinkedList(head1);
head1 = reverseList(head1);
printLinkedList(head1);
}
反转双向链表
1.题目
实现反转双向链表的函数。
要求: 若链表的长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)。
2.算法思路
与单向链表类似,只不过多了一步,需要让节点A的上一节点指向A的下一节点。整个反转代码比反转单向链表就多了这一行。
3.算法思路
public class demotest {
public static void printLinkedList(doubleNode head){
System.out.println("doubleLinkedList:");
doubleNode temp = null;
while(head != null){
System.out.println(head.value + " ");
temp = head; //temp用于记录链表的最后一个节点指针,目的是下面的逆向打印
head = head.next;
}
System.out.println("|"); //此时temp指向的是链表的最后一个节点,所以只需不断向前打印即可
while(temp != null) {
System.out.println(temp.value + " ");
temp = temp.last;
}
}
public static class doubleNode{
//定义一个节点类(包含当前节点的值,和下一节点的指针)
public int value;
public doubleNode last;
public doubleNode next;
public doubleNode(int data){
this.value = data;
}
}
public static doubleNode reverseList(doubleNode head){
//单链表的反转
doubleNode pre=null;
doubleNode next=<