反转单向、双向链表
要求:如果链表长度为N,时间复杂度要求为O(N),额外的空间复杂度要求为O(1)
public class Problem04_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 class DoubleNode { public int value; public DoubleNode next; public DoubleNode last; public DoubleNode(int data) { this.value = data; } } // 逆序双链表函数 public static DoubleNode reverseList(DoubleNode head) { DoubleNode pre = null; DoubleNode next = null; while (head != null) { next = head.next; head.next = pre; head.last = next; pre = head; head = next; } return pre; } // 打印单链表中的数据 public static void printLinkedList(Node head) { System.out.println("LinkedList: "); while (head != null) { System.out.println(head.value + " "); head = head.next; } System.out.println(); } // 打印双链表中的数据 public static void printDoubleLinkedList(DoubleNode head) { System.out.println("DoubleLinkedList: "); DoubleNode end = null; while (head != null) { System.out.println(head.value + " "); head = head.next; } System.out.println(" | "); while (end != null){ System.out.println(end.value + " "); end = end.last; } 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); DoubleNode head2 = new DoubleNode(1); head2.next = new DoubleNode(2); head2.next.last = head2; head2.next.next = new DoubleNode(3); head2.next.next.last = head2.next; head2.next.next.next = new DoubleNode(4); head2.next.next.next.last = head2.next.next; printDoubleLinkedList(head2); printDoubleLinkedList(reverseList(head2)); } }
运行结果:
LinkedList: 1 2 3 LinkedList: 3 2 1 DoubleLinkedList: 1 2 3 4 | DoubleLinkedList: 4 3 2 1 |
日行一善, 日写一撰