輸入一個鏈表,反轉鏈表后,輸出新鏈表的表頭
解法一
說起反轉,第一個想到的肯定是利用堆疊先進后出的特性,這道題當然可以用堆疊來實作,但是對于注釋中那一塊不是很明白,先放著,如果有大佬知道的話求解答
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null)
return null;
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
do {
stack.push(temp);
temp = temp.next;
} while (temp != null);
//如果這里的頭結點的next要不置為空,就會導致遍歷時無限回圈
head.next = null;
ListNode root = stack.pop();
ListNode node = root;
while (!stack.isEmpty()) {
node.next = stack.pop();
node = node.next;
}
return root;
}
}
解法二
最好的辦法就是利用雙指標的方式
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
return null;
// head為當前節點,如果當前節點為空的話,那就什么也不做,直接回傳null;
ListNode pre = null;
ListNode next = null;
// 當前節點是head,pre為當前節點的前一節點,next為當前節點的下一節點
// 需要pre和next的目的是讓當前節點從pre->head->next1->next2變成pre<-head next1->next2
// 即pre讓節點可以反轉所指方向,但反轉之后如果不用next節點保存next1節點的話,此單鏈表就此斷開了
// 所以需要用到pre和next兩個節點
// 1->2->3->4->5
// 1<-2<-3 4->5
while(head!=null){
// 做回圈,如果當前節點不為空的話,始終執行此回圈,此回圈的目的就是讓當前節點從指向next到指向pre
// 如此就可以做到反轉鏈表的效果
// 先用next保存head的下一個節點的資訊,保證單鏈表不會因為失去head節點的原next節點而就此斷裂
next = head.next;
// 保存完next,就可以讓head從指向next變成指向pre了,代碼如下
head.next = pre;
// head指向pre后,就繼續依次反轉下一個節點
// 讓pre,head,next依次向后移動一個節點,繼續下一次的指標反轉
pre = head;
head = next;
}
// 如果head為null的時候,pre就為最后一個節點了,但是鏈表已經反轉完畢,pre就是反轉后鏈表的第一個節點
// 直接輸出pre就是我們想要得到的反轉后的鏈表
return pre;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/135484.html
標籤:其他
