反转单向链表和反转双向链表
单向链表
具体代码
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 void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
System.out.print("原链表:");
print(head1);
System.out.println();
System.out.print("反转后链表:");
print(reverseList(head1));
}
输出结果
双向链表
和单向链表几乎一样,注意last指针的重连即可。
public static DoubleNode reverseList(DoubleNode head){
DoubleNode pre = null;
DoubleNode next = null;
while (head != null){
next = head.next;
head.next = pre;
//last指针重连
head.last = next;
pre = head;
head = next;
}
return pre;
}