反轉單向、雙向鏈表
阿新 • • 發佈:2017-05-17
out 數據 data sel 空間 padding nod color link
要求:如果鏈表長度為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; publicDoubleNode 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 |
反轉單向、雙向鏈表