前面咱們實現了幾種常見的 鏈表 ,接下來,咱們來聊聊如何實現 單鏈表 的反轉。html
示例:node
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Input: NULL
Output: NULL
複製代碼
咱們能夠經過循環遍歷和遞歸這兩種方式來實現鏈表的反轉。git
定義三個指針,分別爲prev、curr、next,而後遍歷全部node結點,並移動這三個指針,改變curr結點的next指向,指向prev結點,實現linkedList的反轉。github
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
}
複製代碼
源碼算法
其實遞歸的實現方式和前面循環的方式很是類似,前者是經過循環來移動指針,後者是經過遞歸來移動指針。bash
定義一個遞歸接口,傳入curr與prev節點做爲參數,內部再將curr的做爲下次遞歸調用的prev入參,curr.next
做爲下次遞歸調用的curr入參。數據結構
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode reverseList(ListNode head){
return reverseRecursively(head, null);
}
public ListNode reverseRecursively(ListNode curr, ListNode prev) {
if(curr == null){
return null;
}
if(curr.next == null){
ListNode head = curr;
curr.next = prev;
return head;
}
ListNode next1 = curr.next;
curr.next = prev;
ListNode head = reverseRecursively(next1, curr);
return head;
}
}
複製代碼
源碼spa
這兩種方式的時間複雜度均爲O(n),空間複雜度均爲O(1)。3d