題目:輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
解析:
①定義一個當前指針head指向當前結點,一個前向指針pre指向前一結點;
②初始的當前指針爲頭結點,前向指針爲null,因爲鏈表反轉後頭結點指向null;
③遍歷鏈表,將當前結點head指向前向結點pre,此時pre需要作爲下一個節點的前向結點,因此賦爲當前結點head。當前結點head移動到下個結點,重複上述操作,知道鏈表遍歷完。
public ListNode ReverseList(ListNode head){
if (head == null) return null;
ListNode pre = null, curnode = null;//curndoe是用來記錄當前結點的下個結點的
while (head!=null){
curnode = head.next;//保存當前結點head的下一結點(不保存會在下一步被改變)
head.next = pre;//當前結點head指向前向節點
pre = head;//將當前結點head保存爲pre作爲下個結點的前向結點
head = curnode;//當前結點移動下個結點
}
return pre;
}