劍指Offer-連結串列-(3)
阿新 • • 發佈:2018-12-05
知識點/資料結構:連結串列
題目描述:
輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。
可能的測試案例:
(1)輸入的連結串列頭指標是nullptr;
(2)輸入的連結串列只有一個節點;
(3)輸入的連結串列有多個節點;
思路:為了正確的反轉一個連結串列,需要調整連結串列中的指標的方向;需要注意為了防止連結串列斷裂,需要定義一些節點來儲存遍歷到的節點的前一個節點和後一個節點。 《如下圖,例子:有三個節點》
public class Solution { public ListNode ReverseList(ListNode head) { if(head==null){ return null; } ListNode pre= null; ListNode next=null; while(head!=null){ next=head.next;//不要考慮head.next是不是為空;是空就讓next指向空。 head.next=pre; pre=head; head=next;//此處是頭尾相連!!! } return pre;//pre最後是一個頭節點。是一個連結串列的頭節點 } }