這是一個常見的考驗 Coding 能力的筆試題。
主要思路就是:
對於每個節點,使用臨時變量記錄原來的前驅和原來的後繼,然後把原來的前驅接到這個節點的後繼上。
代碼如下:
public class 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;
while (head != null){
//記錄原後繼
next = head.next;
//反轉
head.next = pre;
//刷新前驅
pre = head;
//刷新當前節點
head = next;
}
//運行到最後pre是新的頭
return pre;
}
public static class DoubleNode {
public int value;
//前驅
public DoubleNode pre;
//後繼
public DoubleNode next;
public DoubleNode(int data) {
this.value = data;
}
}
//雙向鏈表反轉
public static DoubleNode reverseList(DoubleNode head) {
//記錄原前驅
DoubleNode pre = null;
//記錄原後繼的變量
DoubleNode next;
while (head != null){
//記錄原後繼
next = head.next;
//反轉
head.next = pre;
head.pre = next;
//刷新前驅
pre = head;
//刷新當前節點
head = next;
}
//運行到最後pre是新的頭
return pre;
}
public static void printLinkedList(Node head) {
System.out.print("Linked List: ");
while (head != null) {
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
public static void printDoubleLinkedList(DoubleNode head) {
System.out.print("Double Linked List: ");
DoubleNode end = null;
while (head != null) {
System.out.print(head.value + " ");
end = head;
head = head.next;
}
System.out.print("| ");
while (end != null) {
System.out.print(end.value + " ");
end = end.pre;
}
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.pre = head2;
head2.next.next = new DoubleNode(3);
head2.next.next.pre = head2.next;
head2.next.next.next = new DoubleNode(4);
head2.next.next.next.pre = head2.next.next;
printDoubleLinkedList(head2);
printDoubleLinkedList(reverseList(head2));
}
}
運行結果: