反轉單向鏈表
思想:有好幾種方法:這裏採用的是創建一個新的鏈表來存放新產生的鏈表,把原鏈表的表頭節點依次接到新的鏈表中
代碼:
public static class Node { //定義一個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) { //head是每個要接在鏈表的開頭的那個節點
next = head.next; //要改變的節點
head.next = pre;
pre = head;
head = next;
}
return pre; // 返回倒序的鏈表
}
反轉雙向鏈表
思想:跟單向鏈表的反轉相似,但是這裏要注意它有一個前驅指針,大致思想跟單向的差不多,具體看代碼,這裏再加上測試代碼等
代碼:
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 = 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.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.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鏈表
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));
}
還有其他的方法,可以參考一下;鏈接:點擊