// 鏈表反轉的思路:依次將head後面的節點插入到last後面去即可
// 節點的刪除和插入
public static Node reverseLinkedList(Node head) {
if (head != null) {
Node last = head;
while (last.next != null) {
last = last.next;
}
while (head.next != last) {
// 獲取head後面的第一個節點
Node temp = head.next;
// 刪除head後面的第一個節點
head.next = temp.next;
// 將刪除的節點插入last節點後面
temp.next = last.next;
last.next = temp;
}
return head;
} else {
throw new IllegalArgumentException("head must be not null!");
}
}
算法之鏈表反轉
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.